Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Quiz, background condition doesnt work, using bootstrap

I have quiz app. If user click on answer, I am trying to add green background, if user selected correct answer. Green background is working, but if user selected wrong answer ,I want to add red background , and here is problem , some reason , red background doesn’t work , can you please tell me what I am doing wrong?


{question?.answers.map((item, i) => (
    <button
     className={`btn border w-100 mt-1 ${
      selectedAnswer === 'correct' && item.correct     // condition start here
      ? 'bg-success text-light'                        // green is working
      : selectedAnswer === 'wrong' && !item.correct     //  <<< problem
       ? 'bg-danger text-light'
          : ''   }`}
         key={i}
          disabled={disabledBtn}
                               
          onClick={() => {
              // {} can add more click events
            checkCorrectAnswer(item.correct)
             }}  >
                {item.text}
            </button>
     ))}



  const checkCorrectAnswer = (selected) => {

    setShowNextBtn(true);
    if (selected) {
      if (selected === true) {
         //    <<<<<<<<<<<<<<<<<<<<   checking answer and add color
        setSelectedAnswer(selected === true ? 'correct' : 'wrong');
        setScore((prev) => prev + 1);
      }
    }
    setDisabledBtn(true);
  };

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Your implementation for the method checkCorrectAnswer() looks a little buggy and complicated. Can try following following –

const checkCorrectAnswer = (selected) => {
  setShowNextBtn(true);
  if (selected) {
    setSelectedAnswer('correct');
    setScore((prev) => prev + 1);
  } else {
    setSelectedAnswer('wrong');
  }
  setDisabledBtn(true);
};
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading