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粉1908832252023-09-12 12:13:37
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; }