DEV Community

Pradeep Pradyumna
Pradeep Pradyumna

Posted on • Edited on

Learned how to change the background color of a React function component randomly

Currently, I'm working on a web app using React JS and it has a lot of functional components that I render selectively when required. I have defined styles for almost every component in my App.css file. But, I wanted one of my components to change its background color randomly every time it loads. I wasn't sure of the JS syntax and when I looked upon the internet I didn't get the exact syntax I was looking for.

After some trial and error, I finally cracked a syntax and it worked! So, I thought of sharing with the community here. 😁

import React from "react";

function MyComponent({ name }) {
  // I found this formula
  // here: https://css-tricks.com/snippets/javascript/random-hex-color/
  let randomColor = Math.floor(Math.random() * 16777215).toString(16);

  // The trouble I had was about how to use
  // the variable randomColor in "style:{}" tag
  return (
    <div className="parent-container">
      <div
        className="child-container"
        style={{ backgroundColor: "#" + `${randomColor}` }}
      >
        <h4 className="name">{name}</h4>
      </div>
    </div>
  );
}

export default MyComponent;
Enter fullscreen mode Exit fullscreen mode

I'm not sure if this the only way of doing it. But if there are any other ways too, pls share them in the comments. I would be happy to learn!

Thanks for reading! 

Top comments (0)