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
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:
If you want to make it without ternaries you can also achieve it like so:
you practically cut the jsx code short and insert whatever javascript code you need inside the {}
Can you please check if this code is working as per your requirement.
{item?.price == null && item?.type === ‘Sell’
? ‘Please contact agency’
: item.price !== null && item.price !== undefined
? `$ ${item.price}`
: null}