Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading