I made an app with React that has a search box that displays suggestions to the users as they type. Now I would like to make these suggestions clickable, so when the user clicks on one of them, it will replace the value of the search box.
The input component is:
export function Search(){
const [inputValue, setInputValue] = useState("")
const handleInput = (event) => {
setInputValue(event.target.value)
}
return(
<input value={inputValue} onChange={handleInput}/>
<Suggestions mySuggestions={mySuggestions} setInputValue={setInputValue} />
)
}
And the suggestions component is:
export function Suggestions({setInputValue}){
return (
<div className="suggestions">
<ul>
{mySuggestions.map((suggestion, index) => {
const {meaning} = suggestion._source
return <li onClick={()=> setInputValue({meaning})} key={index}>{meaning}</li>
})}
</ul>
</div>
)
}
};
The 'setInputValue' is working properly in the first component as the value updates as I type, but in the second component, it isn't working. The suggestions are displayed, but when I click on them, the value doesn't update.
Does anyone know what is the problem with my code?
Update:
I tried removing the curly braces from onClick={()=> setInputValue({meaning})}, but it still didn't work. I tried onClick={()=> setInputValue(meaning)}.
const [inputValue, setInputValue] = useState("")your state is a string, though later you update it with an object:onClick={()=> setInputValue({meaning})}. You need to decide what you want, because it can't be both. I would expect it to be:onClick={()=> setInputValue(meaning)}