1

I'm trying to do something in a personal React project. So, I have a list of locations and a search input. When I'm entering something in that input and nothing is found in my locations array I want to show a message like "No result found!". I know how to do this just when I don't use that filter thing.

Here is my code where I'm filtering results by that input:

<input
type="text"
placeholder="Cautare"
value={searchedLocation}
onChange={(e) => { setSearchedLocation(e.target.value); }}
/>
<div className="workspace">
   <div className="locations-group">
      {locations.filter((location) => {
         if (searchedLocation === null) {
            return location;
         } else {
            if(location.name.toLowerCase().includes(searchedLocation.toLowerCase()))
               return location;
            }
         }).map((loc) => {
            return <LocationModel locationName={loc.name} />
         } )}
   </div>
</div>

1 Answer 1

1

Good idea would be to split filter and map, by moving filter outside of jsx tags. To branch between length === 0 and else, you may either use ternary operator inside jsx or do different returns. But for this scenario first seems better.

const App = () => {
  // useState
  
  const filteredLocations = locations.filter((location) => {
    if (searchedLocation === null) {
      return location;
    } else {
      if (location.name.toLowerCase().includes(searchedLocation.toLowerCase())) {
        return location;
      }
    }
  )

  return (
    <>
      // input and everything else

      <div className="workspace">
        <div className="locations-group">
          {filteredLocations.length
            ? filteredLocations.map(loc => <LocationModel locationName={loc.name} />)
            : <div>No result found!</div>
          }
        </div>
      </div>
    </>
  )
}
Sign up to request clarification or add additional context in comments.

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.