Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

252
Vistas
Why my autocomplete input is not working?

Hello newbie here writing my first question, I have an input field and when I type it will filter a json file and it will show the matching places starting with the same letter  ( I'm trying to build a autocomplete search bar for a weather app). the problem that I'm having is that when I click on one of the element it doesn't set the input text to what I  have been clicking..any help would be great! thanks!

Codesandbox here : https://codesandbox.io/s/exciting-fire-vhvl5w

import data from "./city2.list.json";

const SearchBar = () => {
  const [input, setInput] = useState("");
  const [matchesArray, setMatchesArray] = useState([]);
  const [city, setCity] = useState("");

  const getCitySuggestions = (input) => {
    let matches = [];
    if (input !== "") {
      for (let i = 0; i < data.length && matches.length < 10; i++) {
        if (data[i].name.toLowerCase().startsWith(input.toLowerCase())) {
          matches.push({
            id: data[i].id,
            long: data[i].coord.lon,
            lat: data[i].coord.lat,
            name: data[i].name,
            country: data[i].country,
          });
          setMatchesArray(matches);
        }
      }
    }
    return matches;
  };
  useEffect(() => {
    getCitySuggestions(input);
  }, [input]);

  const handleClick = (e) => {
    e.preventDefault();
    let a = setCity(e.target.value);
    console.log("city is..", a);
  };

  return (
    <div>
      <form onSubmit={(e) => handleClick(e)}>
        <input
          type="text"
          name="search"
          id="search"
          placeholder="search..."
          onChange={(e) => setInput(e.target.value)}
        />
        <button type="submit">search..</button>
        {matchesArray.map((item, index) => (
          <div onClick={(e) => handleClick(e)} value={item.name} key={index}>
            {item.name}
          </div>
        ))}
      </form>
    </div>
  );
};

export default SearchBar;```
about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

Actually you are passing wrong detail in function. Let me share correct way.

Now:

<div onClick={(e) => handleClick(e)} value={item.name} key={index}>
            {item.name}
          </div>

Should be:

<div onClick={handleClick.bind(this, item)} value={item.name} key={index}>
            {item.name}
          </div>

And the function should like:

const handleClick = (item) => {
 
    setInput(item.name)
  };

Try this, this will resolve your input filed issue.

about 4 years ago · Juan Pablo Isaza Denunciar

0

You could simply pass the city name as argument to onClick method.

{matchesArray.map((item, index) => (
   <div
    onClick={() => handleClick(item.name)}
    value={item.name}
    key={item.id}
    >
    {item.name}
    </div>
))}

Then inside handleClick method, set city name and input.

const handleClick = (cityName) => {
    setCity((prev) => cityName);
    setInput((prev) => cityName);
  };
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda