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. So if you want to make a search filter in React.js then follow the steps mentioned below.
Creating React Application And Setting Up Project Module: Go inside the folder where you want to initialize your project and then,
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: After this, your project structure will look like this,
Step 4: Open App.js and copy and paste the code written below.
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; |
For Running the Development server, write the command mentioned below,
npm start
Output:
From the multiple available products, we write shoes and then click on the search icon and after that the products which match shoes get filtered and displayed on the screen.