2

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:

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

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

2 Answers 2

1

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>
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you, this answers half the question but how would I also do this for all 3 possibilities? e.g. length = 0, length = 1, length > 1? I want to render the table length = 1 or length > 1 but another message if not.
I already teach u everything tho, but i just edited now
0

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 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>
  )
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.