I am trying something pretty simple i guess, but i cant seem to get it work properly. So i am using an input field to filter out an array of objects, which works medium good at the moment – (that means i am not sure if the condition is set up properly – sometimes it shows the right results, sometimes it doesnt.)
anyway i would like to change the background color depending on if there are objects matching the input or not.
Please can somebody help me fix this? This is my code:
const [searchInput, setSearchInput] = useState('');
const [isValid, setIsValid] = useState(true)
const style = (isValid ? 'searched' : '');
const searchItems = (searchValue) => {
setSearchInput(searchValue)
if (searchInput !== '') {
const filteredData = allData.filter((project) => {
return Object.values(project).join('').toLowerCase().includes(searchInput.toLowerCase())
})
setFilteredResults(filteredData)
setIsValid(true)
}
else{
setFilteredResults(allData)
setIsValid(false)
}
}
and the input:
<label className="searchbar">
<input
className={style}
placeholder="A Visual Practice"
onFocus={(e) => e.target.placeholder = "Search for?"}
onBlur={(e) => e.target.placeholder = "A Visual Practice"}
onChange={(e) => searchItems(e.target.value)}
/>
</label>
After setting the searchInput State, the component will be re-rendered. So what I would is the following:
Use the style state for checking if the input is valid or not and instead of storing a string, store a boolean (true for a valid input). I would call this state isValid and setIsValid.
Before the return of the component, create a constant for your styling
const style = ${isValid ? 'searched' : ''};
Because the component will be re-rendered every time you change a state, the style constant will be changed based on the isValid state. This constant can then be used as a class for your component.