React - dynamically render based on object value

0 votes
38 views
added Mar 14 in React by lcjr First Warrant Officer (11,830 points)

Instead of this:

{item.field_property_type_i === 33 && (
    <span>Non landed</span>
)} 
{item.field_property_type_i === 36 && (
    <span>Landed</span>
)} 
{item.field_property_type_i === 60 && (
    <span>Commercial</span>
)} 
{item.field_property_type_i === 70 && (
    <span>Industrial</span>
)} 

You can simplify the conditional rendering of different property types by using an object to map the property type IDs to their corresponding labels. Then, you can dynamically render the label based on the property type ID. Here's how you can do it:

const cardPropertyType = {
33: 'Non landed',
36: 'Landed',
60: 'Commercial',
70: 'Industrial'
};

//inside JSX
{cardPropertyType[item.field_property_type_i] && (
<span>{cardPropertyType[item.field_property_type_i]}</span>
)}

 

lazacode.org - Malaysia's programming knowledge sharing platform, where everyone can share their finding as reference to others.
...