Use React to write filtering functions
P粉596191963
2023-08-16 20:02:19
<p>I want to create a filter function that fires when an input value event is received in react useState, but when I start typing I can't see it doing anything. This is my Search component</p>
<pre class="brush:php;toolbar:false;">export function Search({categories, onSearch}){
const [searchText, setSearchText] = useState('');
const filterCategories = () => {
const filteredCategories = categories.filter(category =>
category.name.toLowerCase().includes(searchText.toLowerCase())
);
onSearch(filteredCategories);
};
const handleInputChange = event => {
setSearchText(event.target.value);
filterCategories();
};
return (
<div className="flex items-center">
<form className='flex space-x-1' >
<input
type="text"
className="block w-full px-4 py-2 text-purple-700 bg-white border rounded-full focus:border-purple-400 focus:ring-purple-300 focus:outline-none focus:ring focus:ring -opacity-40"
placeholder="Search..."
value={searchText}
onChange={handleInputChange}
/>
</form>
</div>
)
}</pre>
<p>Then use</p> here
<pre class="brush:php;toolbar:false;">const Layout = ({ categories, children }) => {
const [filteredCategories, setFilteredCategories] = useState(categories);
const handleSearch = (filteredCategories) => {
setFilteredCategories(filteredCategories);
};
return (
<div>
{/* ... */}
<Search categories={categories} onSearch={handleSearch} />
{/* ... */}
{children}
</div>
);
};
export default Layout;</pre>
<p>Then this component is used in the Home component</p>
<pre class="brush:php;toolbar:false;">export default function Home({ posts, categories }) {
return (
<Layout categories={categories}>
<div className="mt-20">
<main className="flex flex-col justify-center items-center h-screen pt-10 pb-30">
{/* Render post */}
</main>
</div>
</Layout>
);
}</pre>
<p>Is there anything I should do to make it work? </p>
In the Layout component, you are passing the value of
categories
to your Search component, you may want to passfilteredCategories
(
filteredCategories
is not used, which makes you feel like nothing happened)