ReactJS Controling Style using useState

I coding an app which you get a question with 4 multiple choices , one of them is correct and the other three are false , if the user click on the correct answer the background of that element turns green , otherwise it turns red , i was figuring out a away how to do it useing a 2 useState hook , one if case the answer is correct the other of the answer is wrong , i also used useRef to extract the value from the elemnt and compare it to the correct answer in the ChoosenOption function , how i can switch between different background colors using the useState i mentioned above , or anybetter ways to do this it will be much appreciated.

const [answer, setAnswer] = useState(false);
  const [wrong, setWrong] = useState(false);
  const PargraphValueRef = useRef();
const ChoosenOption = () => {
    const CorrectAnswer = QuestionsList[QuestionNumber].correct;
    if (PargraphValueRef === CorrectAnswer) {
    } else if (PargraphValueRef !== CorrectAnswer) {
          className='' ???''

There is nothing magical about “className”. It is just a component prop that takes a string.

You can just do something like:

className={ wrong ? 'wrongClass' : 'rightClass' }

or whatever you want to name them.

If you have to do a more complicated class string, you can do more complicated math, like:

const questionClass = ??? // some formula or helper function that returns the string you want

and then just

          className={ questionClass }

It’s just a string - do what you want with it.

Does that makes sense?

Thank you , as you see from my code i already created a function called (ChoosenOption) , i have already passed to the ClassName attribute but seems like it doesnt work , so i was in doubt if its correct to do it this way?

I can’t see where you’ve tried what I’ve suggested. This is a standard technique that I have used countless times so I’m reasonably sure it works.

Here as a pen where you can mess around with it yourself.

1 Like

Im sorry i think this is quite different , i want to manipulate the class based on two different useStates , not one ,

There isn’t much difference. I’ve updated the pen for the className to be based on two states.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.