Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to conditional render in react within a loop in a functional component

I know this question has been asked many times, I’ve looked through many stackoverflow posts but I can’t seem to find the exact problem I’m facing. Below is the code:

<tbody>
        {ratioMetrics && Object.entries(metrics).map(([metric, metricReadable]) => (
          <tr key={metric}>
            <td>{ metricReadable }</td>
            {Object.entries(ratioMetrics).map(([key,value]) => (
              <td key={value[metric]}>{ value[metric] }</td>
              // <td key={value[metric]}>{ Intl.NumberFormat('en', { notation: 'compact' }).format(value[metric].toPrecision(4)) }</td>
            ))}
          </tr>
        ))}
</tbody>

Sometimes value[metric] can be null and so the line commented fails as I can’t call toPrecision on something that is null. I therefore only want the commented line to render when value[metric] is not null and if it is null render the line above it instead. ie:

if not null:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

<td key={value[metric]}>{ Intl.NumberFormat('en', { notation: 'compact' }).format(value[metric].toPrecision(4)) }</td>

if null:

<td key={value[metric]}>{ value[metric] }</td>

I tried the following but I don’t think react likes the syntax because the loop already contains {}.

{Object.entries(ratioMetrics).map(([key,value]) => (
      {!value[metric] && <td key={value[metric]}> "" </td>}
      {value[metric] && <td key={value[metric]}>{ Intl.NumberFormat('en', { notation: 'compact' }).format(value[metric].toPrecision(4)) }</td>}
))}

So my question is how do I go about fixing this? Thank you.

>Solution :

You can use a ternary expression to conditionally render the different td elements based on the value of value[metric].

{Object.entries(ratioMetrics).map(([key,value]) => (
  <td key={value[metric]}>
    {value[metric] ? Intl.NumberFormat('en', { notation: 'compact' }).format(value[metric].toPrecision(4)) : ""}
  </td>
))}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading