Implementing Search Filter Functionality in React: A Step-by-Step Guide
Implementing a search filter functionality in a React application can significantly enhance user experience by allowing users to quickly find relevant content. In this guide, we’ll walk through a simple yet effective way to add search filtering to a list of items in your React app.
Step 1: Setting Up Your React App
First, if you haven’t already created a React app, you can do so using Create React App. Open your terminal and run:
npx create-react-app search-filter-app
cd search-filter-app
npm start
Step 2: Sample Data
For this example, we’ll use a static array of objects as our data source. You can create a file named data.js
in the src
directory:
// src/data.js
const data = [
{ id: 1, name: 'Apple' },
{ id: 2, name: 'Banana' },
{ id: 3, name: 'Cherry' },
{ id: 4, name: 'Date' },
{ id: 5, name: 'Fig' },
{ id: 6, name: 'Grape' },
];
export default data;
Step 3: Creating the Search Filter Component
Next, let’s create a component that will handle the search input and display the filtered list. In the src
directory, create a file named SearchFilter.js
:
// src/SearchFilter.js
import React, { useState } from 'react';
import data from './data';
const SearchFilter = () => {
const [searchTerm, setSearchTerm] = useState('');
const handleSearchChange = (event) => {
setSearchTerm(event.target.value);
};
const filteredItems = data.filter(item =>
item.name.toLowerCase().includes(searchTerm.toLowerCase())
);
return (
<div>
<input
type="text"
placeholder="Search..."
value={searchTerm}
onChange={handleSearchChange}
style={{ margin: '20px', padding: '10px', width: '300px' }}
/>
<ul>
{filteredItems.map(item => (
<li key={item.id}>{item.name}</li>
))}
</ul>
</div>
);
};
export default SearchFilter;
Step 4: Integrating the SearchFilter Component
Now, let’s integrate the SearchFilter
component into our main application. Open src/App.js
and update it as follows:
// src/App.js
import React from 'react';
import SearchFilter from './SearchFilter';
const App = () => {
return (
<div>
<h1>Search Filter Example</h1>
<SearchFilter />
</div>
);
};
export default App;
Step 5: Styling the Component
You can add some basic CSS styles for better presentation. Create a file named App.css
or modify the existing one:
/* src/App.css */
body {
font-family: Arial, sans-serif;
background-color: #f4f4f4;
margin: 0;
padding: 20px;
}
h1 {
color: #333;
}
input {
border: 1px solid #ccc;
border-radius: 4px;
}
Step 6: Running Your Application
Now, your application is ready. If you haven’t already, run:
npm start
Open your browser and navigate to http://localhost:3000
. You should see a search input field and a list of fruits. As you type in the search box, the list will dynamically filter based on the input.