Search code examples
reactjsapisearchbar

Enter the selected item in the search bar in React.js


I have the following code:

function App() {
  const [countries,setCountries]= useState([]);
  const [search, setSearch] = useState('');
  

 //Take data from API with useEffect, async/await and try/catch
  useEffect(() => {
    const fetchData = async () => {
      try {
        const response = await axios.get('https://restcountries.com/v2/all');
        setCountries(response.data);
      } catch (error) {
        console.error(error);
      }
    }
    fetchData();
  }, []);

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

  
 
 
  const handleSelect = (country) => { 
    setSearch(country.name);
  }

  

  

  return (
    <>
      <div>
        <SearchBar onChange={(e)=> setSearch(e.target.value)}  />
        {
          <ul className="list">
            {search.length > 0 && filteredCountries.map((country) => (
              <li key={country.name} onClick={() => handleSelect(country)}>
                {country.name}
              </li>
            ))}
          </ul>
        } 
      </div>
      <div className="map-container">

      </div>
    
</>  
  )
}

export default App;

The result is this: List image

How can I select an item from the list, e.g. if I search for Ital, Italy appears and I would like to select it and have it appear in the search bar.

I would like to create a search bar to find a country and select it, it should appear in the search bar after being selected.

CodeSandBox Link: https://codesandbox.io/p/github/pierre1590/Population-Tracker/draft/gallant-gagarin?file=%2Fsrc%2Fcomponents%2FMap%2FMap.js


Solution

  • Add value={search} in your <SearchBar/> component.

    eg: <SearchBar value={search} onChange={(e)=> setSearch(e.target.value)} />

    Below is the full code (I've used a normal input tag in place of your SearchBar component)

    import { useState, useEffect } from "react";
    import axios from 'axios';
    
    
    function App() {
      const [countries,setCountries]= useState([]);
      const [search, setSearch] = useState('');
      
      console.log(search)
    
     //Take data from API with useEffect, async/await and try/catch
      useEffect(() => {
        const fetchData = async () => {
          try {
            const response = await axios.get('https://restcountries.com/v2/all');
            setCountries(response.data);
          } catch (error) {
            console.error(error);
          }
        }
        fetchData();
      }, []);
    
      const filteredCountries = countries.filter((country) => 
        country.name.toLowerCase().includes(search.toLowerCase())
      );
    
      
     
     
      const handleSelect = (country) => { 
        setSearch(country.name);
      }
    
      
    
      
    
      return (
        <>
          <div>
            <input value={search} onChange={(e)=> setSearch(e.target.value)}  />
            {
              <ul className="list">
                {search.length > 0 && filteredCountries.map((country) => (
                  <li key={country.name} onClick={() => handleSelect(country)}>
                    {country.name}
                  </li>
                ))}
              </ul>
            } 
          </div>
          <div className="map-container">
    
          </div>
        
    </>  
      )
    }
    
    export default App;

    CodeSandBox Link - https://codesandbox.io/s/enter-the-selected-item-in-the-search-bar-in-react-js-582rez?file=/src/App.js