skip to Main Content

How do I used if else in jsx?

I know I can do it like this

<h2 className='font-bold text-lx'>$ {item?.price == null && item?.type =='Sell' ? 'Please contact agency' : (item.price) }</h2>

Because when the item?.price == null && item?.type =='Sell' I will show item.price

But if the item?.type =='Rent' I need to show item.rentMoney

So how could I modify it?

if the item?.price == null && item?.type =='Sell' show item.price and
the item?.type =='Rent' show item.rentMoney

4

Answers


  1. It’s been a while since I last wrote in React.js but I think you can fulfill this requirement by using a ternary operator INSIDE a ternary operator:

    <h2 className='font-bold text-lx'>
      {item?.price == null && item?.type === 'Sell' ? 'Please contact agency' : 
        (item?.type === 'Rent' ? item?.rentMoney : item?.price)}
    </h2>
    

    If you want to make it without ternaries you can also achieve it like so:

    <h2 className='font-bold text-lx'>
      {(() => {
        if (item?.price == null && item?.type === 'Sell') {
          return 'Please contact agency';
        } else if (item?.type === 'Rent') {
          return item?.rentMoney;
        } else {
          return item?.price;
        }
      })()}
    </h2>
    

    you practically cut the jsx code short and insert whatever javascript code you need inside the {}

    Login or Signup to reply.
  2.  <h2 className='font-bold text-lx'>$ {item?.price == null && item?.type =='Sell' ? (item.price) :(item.rentMoney)}</h2>
    

    Can you please check if this code is working as per your requirement.

    Login or Signup to reply.
  3. <h2 className='font-bold text-lx'>
     {(item?.price == null && item?.type === 'Sell')
        ? item.price
        : item?.type === 'Rent'
        ? item.rentMoney
        : 'Please contact agency'}
    </h2>
    
    Login or Signup to reply.
  4. {item?.price == null && item?.type === ‘Sell’
    ? ‘Please contact agency’
    : item.price !== null && item.price !== undefined
    ? `$ ${item.price}`
    : null}

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search