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;```