It was working fine, but it stopped working.
const SearchBar = ({ carddata}) => {
let arr = [];
function searchResult(e) {
if (e.key === "Enter") {
if (e.target.value === "") return;
arr = [];
carddata.filter((result) => {
if (`${result.heading}`.toLowerCase().match(e.target.value)) {
arr.push(result);
console.log(arr)
}
});
}
}
return (
<div className="flex">
<input
onKeyDown={searchResult}
className="search-input w-100 br bb fw4"
type="text"
placeholder="Search here..."
></input>
<SearchIcon
className="search-icon h2 br bb hover-black"
style={{ fill: "red" }}
sx={{ fontSize: 40 }}
/>
</div>
);
};
export default SearchBar;
CodePudding user response:
There is no value attribute in yourinput tag to update.
<input
value={somestate}
onChange={e=> setState(e.target.value)}
/>
This will update the value in your input as you type.
CodePudding user response:
I think it is because you are not passing the event to the function when writing onKeyDown, try passing the event to the function like this and see if it would work:
<input
onKeyDown={(e)=>searchResult(e)}
className="search-input w-100 br bb fw4"
type="text"
placeholder="Search here..."
></input>
CodePudding user response:
I made you an example, but i couldn't tor try it if you share the content of carddate array, maybe i can solve and explain it more detailed!
You cen read more about the controlled inputs here: https://reactjs.org/docs/forms.html
import React, {useState, useEffect} from "react";
const SearchBar = ({ carddata}) => {
const [searchValue, setSearchValue]
let arr = [];
useEffect()=>{
function searchResult() {
if (e.key === "Enter") {
if (searchValue === "") return;
arr = [];
carddata.filter((result) => {
if (`${result.heading}`.toLowerCase().match(e.target.value)) {
arr.push(result);
console.log(arr)
}
});
}
}, [searchValue]
}
return (
<div className="flex">
<input
onChange={e=>setSearchValue(e.target.value)}
className="search-input w-100 br bb fw4"
type="text"
placeholder="Search here..."
value="searchValue"
/>
<SearchIcon
className="search-icon h2 br bb hover-black"
style={{ fill: "red" }}
sx={{ fontSize: 40 }}
/>
</div>
);
};
export default SearchBar;
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
