How to implement search filter functionality in React JS ?
Last Updated :
17 Dec, 2023
The search filter is used in various projects which generally returns all the matching products of the name you entered which could be used at many different places and the logic remains the same for it.
Prerequisites:
Approach to implement search filter functionality:
- State Initialization: Initialize the state variables
productList
and searchVal
using the useState
hook, with productList
containing an array of product names.
- Search Functionality: Implement the
handleSearchClick
function to filter products based on the search input. If the search input is empty, reset the products to the original list.
- User Interface: Create a simple UI using an input field for search and the BsSearch icon from
react-icons/bs
. Display the filtered or original product list based on the search term.
Steps to create React Application And Setting Up Project Module:
Step 1: Create a React application using the following command:
npx create-react-app project_name
Step 2: After creating your project folder i.e. project_name, jump into it by writing this command:
cd project_name
Step 3: After this, add react icons to the project by writing this command:
npm install react-icons --save
Project Structure:
Project Structure
The updated dependencies in package.json file will look like:
"dependencies": {
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-icons": "^4.12.0",
"react-scripts": "5.0.1",
"web-vitals": "^2.1.4",
}
Example: Below is the code example of search filter functionality.
Javascript
import React, { useState } from 'react'
import './App.css' ;
import { BsSearch } from 'react-icons/bs' ;
function App() {
const productList = [ "blue pant"
, "black pant"
, "blue shirt"
, "black shoes"
, "brown shoes"
, "white pant"
, "white shoes"
, "red shirt"
, "gray pant"
, "white shirt"
, "golden shoes"
, "dark pant"
, "pink shirt"
, "yellow pant" ];
const [products, setProducts] = useState(productList);
const [searchVal, setSearchVal] = useState( "" );
function handleSearchClick() {
if (searchVal === "" ) { setProducts(productList); return ; }
const filterBySearch = productList.filter((item) => {
if (item.toLowerCase()
.includes(searchVal.toLowerCase())) { return item; }
})
setProducts(filterBySearch);
}
const mystyle = {
marginLeft: "600px" ,
marginTop: "20px" ,
fontWeight: "700"
};
return (
<div>
<div style={mystyle}>
<input onChange={e => setSearchVal(e.target.value)}>
</input>
<BsSearch onClick={handleSearchClick} />
</div>
<div>
{products.map((product) => {
return (
<div style={mystyle}>{product}</div>
)
})
}
</div>
</div>
);
}
export default App;
|
Steps to run the application: Type the following command in the terminal
npm start
Output:
Output
Share your thoughts in the comments
Please Login to comment...