Live search in React JS allows users to see search results update in real-time as they type. This provides a smoother and more interactive user experience compared to traditional search methods.
Here's a breakdown of how you can implement live search in your React JS application:
1. State Management
- Use React's state to store the current search query.
- Update the state whenever the user types in the search input.
2. Event Handling
- Attach an
onChange
event handler to the search input. - Inside the handler, update the state with the new value from the input.
3. Filtering Data
- Use a filtering function to process the data based on the current search query.
- This function should compare the search query with relevant fields in your data.
- Return the filtered data to be displayed.
4. Rendering Results
- Conditionally render the search results based on the filtered data.
- If the filtered data is empty, display a message indicating no results found.
- Update the search results dynamically whenever the state changes.
Example
import React, { useState } from 'react';
const data = [
{ name: 'Apple', category: 'Fruit' },
{ name: 'Banana', category: 'Fruit' },
{ name: 'Carrot', category: 'Vegetable' },
];
function App() {
const [searchTerm, setSearchTerm] = useState('');
const handleSearchChange = (event) => {
setSearchTerm(event.target.value);
};
const filteredData = data.filter((item) =>
item.name.toLowerCase().includes(searchTerm.toLowerCase())
);
return (
<div>
<input
type="text"
placeholder="Search..."
value={searchTerm}
onChange={handleSearchChange}
/>
<ul>
{filteredData.map((item) => (
<li key={item.name}>{item.name}</li>
))}
</ul>
</div>
);
}
export default App;
This example demonstrates the basic principles of implementing live search in React JS. You can adapt this code to your specific needs and data structure.