React - Change style of individual <li> created with .map() function

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:

  1. onClick on each of the <li> calls the clickAnswer() function which changes the answerSelection state from either true or false
  2. 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.

That’s because there is no differentiation between different lis in clickAnswer.
You’re probably going to do something with selected answers anyway, so why not think about that case and then return to highlight.

1 Like

You need to specify which list item is selected, that’s the state needed in the parent list. The individual list items may also have some state themselves.

1 Like