'How to add a specific message when an array length is 0?

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>


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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Dmig