How to implement random mapping of element background?
P粉286046715
P粉286046715 2023-09-11 22:32:31
0
1
494

I want to randomly set the background color of each element

But when I insert it into the following code, the background color becomes transparent:

{
  modules.map((module, index) => (
    <div className='carousel-module shadow'
      style={{ background: "#" + Math.floor(Math.random()*16777215).toString(16)}}
    >
      <p className='module-element-text'>{module.name ? module.name : "N/A"}</p>
      <p className='module-element-text'>{module.code ? module.code : "N/A"}</p>
      <Button onClick={() => setShow(false)}
          variant="success" className='modules-list-button'>
          Load
      </Button>
    </div>
  ))
}

Would be great to hear your suggestions on how to make it work.

P粉286046715
P粉286046715

reply all(1)
P粉190883225

This is the function I use to generate hex colors. Your method might introduce an alpha channel into the color, making it transparent.

function randomHexColor() {
    let toHex = function (n) {
        let hex = n.toString(16);
        while (hex.length < 2) { hex = '0' + hex; }
        return hex;
    };
    let rr = toHex(Math.floor(Math.random() * 256));
    let gg = toHex(Math.floor(Math.random() * 256));
    let bb = toHex(Math.floor(Math.random() * 256));
    return '#' + rr + gg + bb;
}
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template