Home > Mobile >  Use ternary operator to change className in React
Use ternary operator to change className in React

Time:06-22

I'm making a quiz app in React/Typescript using Bootstrap. I want to make it so that the buttons use the bg-light style before the user clicks on it.

When the user selects an answer, the button should switch to bg-success if its the correct answer or bg-danger if its the wrong one.

So far what I've got is the following:

className={`answers btn btn-light && ${
    correct === ans ? 'btn-success' : 'btn-danger'
}`}

Whenever I try this, the buttons stay as btn-light. I tried switching btn-light with btn-secondary, but all the answers immediately used either btn-success or btn-danger based on whether or not they were the right answer, even before being selected.

How do I get them to switch to the right className based on whether or not they're the correct answer and only after the user has clicked on an answer?

CodePudding user response:

The reason it won't ever switch from btn-light is that there's nothing that turns it off. One solution would be having a separate variable that sees if you're hovering on the button, and a ternary operator that looks something like this:

<element-name className={`answers btn ${
    correct !== ans && hover ? 'btn-light' : ''
} ${
    correct === ans ? 'btn-success' : 'btn-danger'
}`}>

CodePudding user response:

Seems to me more like a string template than a ternary operator.

I would instead calculate the class in a variable rather than put it directly into the CSS

const correct === ans ? 'btn-success' : 'btn-danger';
className={`answers btn btn-light ${correct}`}

but I think you can do this:

 className={`answers btn btn-light ${ correct === ans ? 'btn-success' : 'btn-danger'}`}
  • Related