Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

251
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda