Skip to content
Advertisement

Multiple conditions/operators to show/hide html elements in React (NextJS)

I’m looking to display some html in my React/Next.js web app based on conditional logic. I got the basics working but having issues showing the same html if multiple variable conditions are true. For example, the following code works fine.

{category === 'ford' &&
   <div>Car</div>
}

{category === 'harley' &&
   <div>Motorcycle</div>
}

I’m having issues showing multiple variables as true. The following code doesn’t work but show the logic I’m after.

{category === 'ford' || category === 'toyota' &&  
   <div>Car</div>
}

//this code doesn't work. 

I realise a simple answer is to separate operators for each separate condition, however i’m trying to avoid duplicating the html <div>Car</div> (as in my actual application contains large forms in this section).

Advertisement

Answer

You will need to wrap the OR-Condition in parentheses like so:

(category === 'ford' || category === 'toyota') && <div>Car</div>
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement