简体   繁体   中英

How can i target specific button's styling with onClick function if i have the same onClick function attached to multiple buttons?

I'm trying to create a Trivia app in React, but I'm having trouble changing the background color after the user selected the answer from the given options. I'm trying to do the freeCodeCamp's quiz app with some personal changes.

What it currently does is that it colors every single button green or red depending if the answer was correct or wrong and I would like to target only the specific button that has been clicked with the backgroundColor change and leave the rest as they were.

So, here I have a div where i map out the answer options on different buttons:

        <div className='answer-Section'>
          {currentQuestion.answerOptions.map((elem) => (
            <button
              className='answer-Button'
              onClick={() => handleAnswerClick(elem.isCorrect)}
              style={{
                backgroundColor: isAnswered ? bgAnswered : bgNeutral,
              }}
            >
              {elem.answerText}
            </button>
          ))}
        </div>

And here is the onClick event's handler on the mapped buttons:

const handleAnswerClick = (isCorrect) => {
setIsAnswered(true)
isCorrect ? setScore(score + 1) : setScore(score)
isCorrect ? setBgAnswered('green') : setBgAnswered('red')
setTimeout(() => findNextQuestion(), 1000)}


const findNextQuestion = () => {
setIsAnswered(false)
const nextQuestion = currentQuestionNumber + 1
if (nextQuestion === questions.length) {
  setShowScore(true)
} else {
  setCurrentQuestionNumber(nextQuestion)
}}

There are a couple of ways to do this. The simplest would be to store not just whether the question was answered, but which answer was chosen. In the code below, I've also avoided using the bgAnswered state variable, instead just computing the desired color inline.

        [answer, setAnswer] = useState();
        //...
        <div className='answer-Section'>
          {currentQuestion.answerOptions.map((elem, i) => (
            <button
              className='answer-Button'
              onClick={() => handleAnswerClick(elem.isCorrect, i)}
              style={{
                backgroundColor: answer === i ? (elem.isCorrect ? 'green' : 'red') : bgNeutral,
              }}
            >
              {elem.answerText}
            </button>
          ))}
        </div>
const handleAnswerClick = (isCorrect, i) => {
  setAnswer(i);
  if (isCorrect) setScore(score + 1);
  setTimeout(() => findNextQuestion(), 1000)
};

Another option would be to make bgAnswered into an array of values, one for each answer. But that seems unnecessary in this case.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM