I'm trying to solve this exercise where the array contains 10 objects such as
arr = [{txt: "txt1", color: "red"},
{txt: "txt2", color: "green"}, {txt: "txt3", color: "blue"},...]
When I click a button, it should show up a random color which I know how to do but I'm not sure how to also show how many times each color shows up.
I set up my function as below:
const countColors = (props) => {
const arr = [{txt: "txt1", color: "red"},
{txt: "txt2", color: "green"}, {txt: "txt3", color: "blue"},...]
const [count, setCount] = useState(0);
const choice = () => {
const randIdx = Math.floor(Math.random() * arr.length);
return arr[randIdx];
};
const updateScore = () => {
let randColor = choice(props.arr).color;
if (randColor === 'red') {
return setCount((count) => count + 1)
} else if (randColor === 'green') {
return setCount((count) => count + 1);
} else {
return setCount((count) => count + 1);
}
};
const clickHandler = () => {
setCount(updateScore);
}
return (
<ul>
<li>Red Counts: {updateScore}</li>
<li>Green Counts: {updateScore}.
</li>
<li>Blue Counts: {updateScore}</li>
</ul>
<button onClick={clickHandler}>Click</button>
)
};
I keep getting "NaN" or "undefined" when I check the state with the react dev tool.
I wonder if I need to set up 3 states for counting each color.