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

Handling array length in React

I have an array of results I’m wanting to render in a table:

const ScanOutput = () => (
  <div class="results">
    <h1>
      <b>Scan Results</b>
    </h1>
    <h3>{results.length} results returned</h3>
    <table class="styled-table">
      <thead>
        <tr>
          <th>ID</th>
          <th>Name</th>
        </tr>
      </thead>
      <tbody>
        {results.map((result) => (
          <tr>
            <td>{result.id}</td>
            <td>{result.name}</td>
          </tr>
        ))}
      </tbody>
    </table>
  </div>
);

This works, but I’d like to add some extra features – for example, if no results are returned (e.g. results.length == 0) I’d like to render "No results found" instead of an empty table. Furthermore, I’d also like to make it so that with this section here:

<h3>{results.length} results returned</h3>

If only 1 result is returned it renders this instead:

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

<h3>{results.length} result returned</h3>

What’s the cleanest way to do this in React?

>Solution :

You can render conditionally.

<div class="results">
{result?.length > 0 ?
 <>
  <h1>
   <b>Scan Results</b>
  </h1>
  <h3>{results.length} results returned</h3>
  <table class="styled-table">
   {...}
  </table>
 </>
:
 <h1>No results found</h1>
}
</div>
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