Home > Software design >  React: How to render a fallback for a TypeAhead component when search yields no match?
React: How to render a fallback for a TypeAhead component when search yields no match?

Time:03-20

I working on a Typeahead component in react.

Presently I am just filtering through the data via an text input based and then mapping over it to display filtered options to the DOM. That is coming along but i'd like to display "No items found" if the search yields nothing.

The following is how I am returning the <li></li> items:

   <ul className="search-container__dropdown" onClick={(e) => e.stopPropagation()} style={{ display: show ? 'block' : 'none' }}>
      {comments.length > 0 ? comments
        .filter(({ body, name }) => {
          if (!input) return true;
          if (body.includes(input) || name.includes(input)) {
            return true;
          }
          return false
        })
        .map(({ id, name, body, notfound }, index, arr) => {
          return (
            <li onClick={() => handleClick(id)} className={`search-container__option ${id === cur_section ? "active" : ""}`}
              key={id}
              value={name}>
              <strong>name: </strong>{name},<br />
              <strong>body: </strong>{body}
            </li>
          )
        }) : <NothingFound />}
    </ul>

This is the NothingFound component:

  function NothingFound() {
    return <li>Nothing found</li>
  }

What am I missing?

Thanks in advance!

CodePudding user response:

You have to filter first and then check the length of the filtered comments like so:

 const filteredComments = comments
  .filter(({ body, name }) => {
    if (!input) return true;
    if (body.includes(input) || name.includes(input)) {
      return true;
    }
    return false;
 })
  
   return (<main>
          ...
          {filteredComments.length > 0 ? (
            filteredComments
              .map(({ id, name, body, notfound }, index, arr) => {
           return (
              <li ...
  • Related