Home > Software engineering >  Handling array length in React
Handling array length in React

Time:04-16

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

const ScanOutput = () => (
  <div >
    <h1>
      <b>Scan Results</b>
    </h1>
    <h3>{results.length} results returned</h3>
    <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:

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

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

CodePudding user response:

You can render conditionally.

<div >
{result?.length > 0 ?
 <>
  <h1>
   <b>Scan Results</b>
  </h1>
  <h3>{results.length} results returned</h3>
  <table >
   {...}
  </table>
 </>
:
 <h1>No results found</h1>
}
</div>

CodePudding user response:

You can create a new component for the results table

const ResultsTable = ({ results }) => {
  if (results?.length === 0) return <h3>No results found</h3>;
  if (results?.length === 1) return ...;

  return (
    <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>
  )
}
  • Related