To implement a search filter in React, you can follow these basic steps:
- State Setup Create a state to hold your data and another state to hold the search input.
const [data, setData] = useState(initialData);
const [searchInput, setSearchInput] = useState('');
- Handling Search Input Update the search input as the user types in the search box.
const handleSearch = (e) => {
setSearchInput(e.target.value);
};
- Filtering the Data Use the filter() method to filter the data based on the search input.
const filteredData = data.filter(item =>
item.name.toLowerCase().includes(searchInput.toLowerCase())
);
- Displaying the Results Map through the filtered data and display the results.
return (
<div>
<input type="text" placeholder="Search..." onChange={handleSearch} />
<ul>
{filteredData.map(item => (
<li key={item.id}>{item.name}</li>
))}
</ul>
</div>
);
Example Code
Here's a complete example based on the above explanation:
import React, { useState } from 'react';
const SearchFilter = () => {
const initialData = [
{ id: 1, name: 'John Doe' },
{ id: 2, name: 'Jane Smith' },
{ id: 3, name: 'Peter Parker' },
];
const [searchInput, setSearchInput] = useState('');
const filteredData = initialData.filter(item =>
item.name.toLowerCase().includes(searchInput.toLowerCase())
);
return (
<div>
<input
type="text"
placeholder="Search..."
onChange={(e) => setSearchInput(e.target.value)}
/>
<ul>
{filteredData.map((item) => (
<li key={item.id}>{item.name}</li>
))}
</ul>
</div>
);
};
export default SearchFilter;
For more detailed tutorials, you can explore:
freeCodeCamp's Guide(
freeCodeCamp
)
KindaCode's Tutorial(
KindaCode
)
Top comments (0)