DEV Community

Pradeep Pradyumna
Pradeep Pradyumna

Posted on • Edited on

3 2

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! 

Speedy emails, satisfied customers

Postmark Image

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay