Is there a way I can conditionally render a value in a table if it is not undefined?

Viewed 26

I am currently trying to develop a table dashboard for a list of properties for the owner to see. And the issue that I'm having is that when I'm trying to display the tenant information, some of the properties don't have tenants(the data called rentalInfo in the JSON is "undefined") and I'm trying to conditionally render when the property does have a tenant, only then I display the tenant's name.

Here's the code for my Table:

import './table.css'
export default function Table(props){
  const properties = props.data;
  console.log(properties[4].rentalInfo[0].tenant_first_name,typeof(properties[4].rentalInfo[0].tenant_first_name))
  const fourth_tenant = properties[4].rentalInfo[0].tenant_first_name

  const rows = properties.map((row, index)=>{
    return(

      <tr>
        <th>{row.rentalInfo.tenant_first_name !== 'undefined'?fourth_tenant:"No tenant at the moment"}</th>
      </tr>
    )
  
  })
    return(
      <div>
      <table>
        <thead>
          <tr>
            <th>Tenant</th>
          </tr>
        </thead>
        <tbody>
          {rows}
        </tbody>
      </table>
    </div>
    )
  }

Here's the code where I call the Table Function along with my Axios.get call

export default function OwnerDashboard2(){
    const [dataTable, setDataTable] = useState([]);

    useEffect(() => {
        axios.get("https://t00axvabvb.execute-api.us-west-1.amazonaws.com/dev/propertiesOwner?owner_id=100-000003")
        .then(res => {setDataTable(res.data.result)})
          .catch(err => console.log(err))
      }, []);

  
    
    return(
        
        <div className="OwnerDashboard2">
                <Row>
                    <Col xs={2}><Navbar/></Col>
                    <Col>{dataTable.length!==0 && <Table data ={dataTable}/>}</Col>
                </Row>
        </div>
    )
}

I tried using <th>{row.rentalInfo.tenant_first_name !== 'undefined'?fourth_tenant:"No tenant at the moment"}</th> but the issue is it's still displaying the only tenant in all the properties(fourth_tenant) for each column.

1 Answers

you can use !! to convert the value to boolean type

just like this:

!!row.rentalInfo.tenant_first_name ? row.rentalInfo.tenant_first_name : "tenant is undefined"
Related