How would I only show data when searched in input?

Viewed 60

I'm learning react and am making a simple app that allows users to search for countries from an api. I have successfully fetched the api and set it to some state and created a filter component for searches in a text input. However I would like to show nothing until the user types in the search input which would then show the countries matching the letters typed. What is the most used way of doing this?

const App = () => {
  const [countries, setCountry] = useState([]) 
  const [search, setSearch] = useState('')


  useEffect(() => {
    console.log('effect')
    axios
    .get(`https://restcountries.eu/rest/v2/all`)
    .then(response => {
      console.log(response,'promise fulfiled')
      setCountry(response.data)
    })
  }, [])

  const handleSearch = (e) => {
    setSearch(e.target.value)
  }

  const filter = countries.filter(country =>
    country.name.toLowerCase().includes(search.toLowerCase()) 
    );


  return (
    <div className="App">
    Search Country: 
    <input type='text' onChange={handleSearch}/>
    <Country filter={filter} />
    </div>
  );
}
const Country = ({filter}) => {
    return(
        <ul style={{listStyle: 'none'}}>
        {
        filter.map(country =>
          <li key={country.name}>
            {country.name}
          </li>)
        }
      </ul>
    )

This is the current code, however it shows all countries from the api. I would like to show no countries until user types in input box. Thanks.

1 Answers

Just have a conditional render for <Country />.

Only display the list of countries if search is supplied.

{ search && <Country filter={filter} /> }

Demo

Related