skip to Main Content

I have a react component in which I need to change the color of the p tag every time the page refreshes. I defined the arrow function to generate a random color. Then I used the style attribute to give it a color generated by function. However, when I run and inspect the element I see the blue color in the module.css file which I already removed from the file.

arrow function to generate random color

const getDifferentColors = () => {
  const r = Math.floor(Math.random() * 256);
  const g = Math.floor(Math.random() * 256);
  const b = Math.floor(Math.random() * 256);
  return `rgba(${r},${g},${b},0.8)`;
};

p tag which I am trying to change

 <p className={styles["contributor-title"]} style={{color:`${getDifferentColors()}`}}>Location of Contributors</p>

and module.css code for the class

.contributor-title {
    text-align: center;
    margin: 20px 0px 10px 0px;
    font-size: 500%;
    font-family: "Mefika", sans-serif;
    /* color: blue; */
}

And I am attaching photo of inspect element:
enter image description here

2

Answers


  1. try writing

    import React from 'react';
    import './module.css';
    
    const getDifferentColors = () => {
      const r = Math.floor(Math.random() * 256);
      const g = Math.floor(Math.random() * 256);
      const b = Math.floor(Math.random() * 256);
      return `rgba(${r},${g},${b},0.8)`;
    };
    
    export default function App() {
      let className = 'contributor-title';
      return (
        <div>
          <p className={className} style={{ color: `${getDifferentColors()}` }}>
            Location of Contributors
          </p>
        </div>
      );
    }
    

    it worked for me

    Login or Signup to reply.
  2. Either you have some mistake where your inlined color function is called or the specificity of the other selector is too high which I kinda doubt.

    Anyways try checking what your html looks and also try using a !important.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search