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

Time:09-29

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).

CodePudding user response:

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

(category === 'ford' || category === 'toyota') && <div>Car</div>

CodePudding user response:

you can also make use of Array includes method

  • I would make an array for e.g.

       const cars = ["honda", "toyota", ....];
       const motorcycle = ["euler", "ducati", ...];
    
       {cars.includes(category) ? <div> cars </div> : <div> motorcycles </div> }
    

CodePudding user response:

const isCarCategory = ["ford", "toyota"].includes(category);

const isMotorcycleCategory = ["harley"].includes(category);

return (
  <div>
    {isCarCategory && <div>Car</div>}
    {isMotorcycleCategory && <div>Motorcycle</div>}
  </div>
);


CodePudding user response:

Just wrap your condition inside parenthesis. Parenthesis must be used, if multiple conditions needs to be checked. Check this link about Precedence And Associativity https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Operator_Precedence

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

CodePudding user response:

you can wrap it all in a different function and use a switch statement (or arrays) to handle not managed category

like this

const renderVehicle = (category) => {
 switch(category) {
  case 'honda':
  case 'ford':
    return <div>Car</div>
  case 'harley':
    return <div>Motorcycle</div>
  default: 
    return <div>Not found</div>
 }
}

const renderVehicle2 = (category) => {
  const cars = ['honda', 'ford']
  const motorcycles = ['harley']
  
  if(cars.includes(category)){
    return <div>Car</div>
  }
  
  if(motorcycles.includes(category)){
    return <div>Motorcycle</div>
  }
  return <div>Not found</div>
}

CodePudding user response:

the simple answer is to wrap the condition in ()

{(category === 'ford' || category === 'toyota') &&  
   <div>Car</div>
}
  • Related