I'm trying to figure out how to solve a color boxes exercise that applies useState hook concept. Given an array that contains 12 different unique colors, initially the state will show 12 divs with a corresponding color. Upon clicking the button, only randomly chosen div will change to a random color(out of the 12 given colors) as well as flagging that div with the message "changed" on the div. So far I was able to make the color box container showing each color on a div. I see the state is changing to a random color every time when I click. But I don't know how to make only that random div to change the color and show the message. Does this problem require a unique id for each color for tracking change of the state?
import React, { useState } from 'react';
import ColorBox from './ColorBox';
import {choice} from './colorHelpers';
const ColorBoxes = () => {
const [ boxes, setBoxes] = useState(colors);
const [msg, setMsg] = useState(null);
const clickHandler = () => {
setBoxes(()=>choice(colors));
setMsg('changed');
};
return (
<>
{colors.map((color,i) =>{
return(
<div>
<ColorBox key={i} color={color} />{color}
</div>
);
})}
<button onClick={clickHandler}>Change Color!</button>
</>
);
};
import React from 'react';
import './ColorBox.css';
const ColorBox = ({ color }) => {
return <div className="colorBox" style={{ backgroundColor: color }} />;
};
export default ColorBox;
const choice = (arr) => {
const randIdx = Math.floor(Math.random() * arr.length);
return arr[randIdx];
};
export { choice };