I am refreshing on React and am working on creating new divs with random colors when I push a button. So far, I have been able to get the divs to appear when I push the button but they are not being assigned a background color. I am using a function 'randomgRgb' to generate a random color and put into an array in the state of the component. I then am mapping the array and using the random color to create my background to the div.
What am I missing?
import React, { useState } from 'react'
import { Button, } from 'react';
const ColorScreen = (props) => {
const [colors, setColors] = useState([])
console.log(colors);
const colorDivs = colors.map((color,i) =>
<li key ={i}><div style={{height:100, width:100, backgroundColor:{color} }}></div></li>
)
return (
<div>
<div style={{height:100, width:100, backgroundColor: randomRGb() }}></div>
<button onClick={() =>
setColors([...colors, randomRGb()])
}> Add a Color</button>
<ul>{colorDivs}</ul>
</div>
)
}
const randomRGb = () => {
const red = Math.floor(Math.random()*256);
const green = Math.floor(Math.random()*256);
const blue = Math.floor(Math.random()*256);
return `rgb(${red},${green},${blue})`
}
export default ColorScreen;
CodePudding user response:
It should be backgroundColor:color and not backgroundColor: {color}
Thanks yousoumar
CodePudding user response:
in this statement just remove the curlies around color and it works fine.
<li key ={i}><div style={{height:100, width:100, backgroundColor:{color} }}></div></li>
CodePudding user response:
Remove the brackets in backgroundColor: {color}
. It should be backgroundColor: color