I’m trying to toggle the background color of an individual <li> when it is clicked.
The <li> 's are created dynamically (using .map()) , based on an array which contains quiz questions in the component’s state:
let quizQ = [
{
"Question": "What is the capital of France?",
"Choices": ["London", "Los Angeles", "Luxembourg", "Paris"]
},
{
"Question" : "What is the capital of California?",
"Choices": ["Sydney", "Kansas", "New York", "Los Angeles"]
}
];
I am using a functional component to do this.
Which is currently doing the following:
- onClick on each of the <li> calls the clickAnswer() function which changes the answerSelection state from either true or false
- This toggle between true and false changes the variable in className to a CSS class that has either a blue or white background
State & onClick function:
const [answerSelection, setAnswerSelection] = useState(false);
let clickAnswer = () => answerSelection ? setAnswerSelection(false) : setAnswerSelection(true);
let answerColor = answerSelection ? "blueAnswer" : "whiteAnswer";
Mapped <li>
<ul>
{quizQ[quesNumber]["Choices"].map( (item, index) => <li className={`quizChoices ${answerColor}${index}`} onClick={() => clickAnswer()} key={item} style={{textAlign: "left"}}>{item}</li>) }
</ul>
The issue is that currently the color change affects all of the <li>'s instead of only the 1 that is clicked, because the answerColor variable is applied to all of the <li>'s.
I just can’t seem to wrap my head around how this could be done in React.