Source: features/pokemons/PokemonSearchResults.jsx

  1. import { useSelector } from 'react-redux'
  2. import PokemonCard from './PokemonCard'
  3. export default function PokemonSearchResults() {
  4. const {
  5. filteredPokemons,
  6. searchQuery,
  7. typeFilter,
  8. abilityFilter,
  9. sortBy
  10. } = useSelector(state => state.pokemons);
  11. /**
  12. * To check if a search exists
  13. * @const searchExists
  14. */
  15. const searchExists = Boolean(searchQuery || typeFilter || abilityFilter || sortBy);
  16. /**
  17. * Renders the filtered Pokemon cards if the search exists and returns search results.
  18. * It the search exists, but returns no results, the user is notified.
  19. * @member filteredPokemonsElements
  20. * @returns {JSX.Element[]} The array of rendered Pokemon cards.
  21. */
  22. let filteredPokemonsElements;
  23. if (filteredPokemons.length > 0 && searchExists) {
  24. filteredPokemonsElements = (
  25. <div>
  26. <div>
  27. {
  28. searchExists &&
  29. <p>{filteredPokemons.length} Pokémon matches your search.</p>
  30. }
  31. </div>
  32. <div className='search--pokemons-list'>
  33. {
  34. filteredPokemons.map(pokemon =>
  35. <PokemonCard key={pokemon.id} pokemon={pokemon} />)
  36. }
  37. </div>
  38. </div>
  39. )
  40. }
  41. if (searchExists && filteredPokemons.length === 0) {
  42. filteredPokemonsElements = <p>No Pokémon matches your search.</p>
  43. }
  44. return (
  45. <section className='search--results'>
  46. {searchExists && <h2>Search Results</h2>}
  47. {filteredPokemonsElements}
  48. </section>
  49. )
  50. }