React is a JavaScript framework mainly focused on building interactive and dynamic user interfaces to enhance user experience. Using ReactJS, we can create a search filter or search bar for websites or React projects.
A search filter is a tool or feature that lets users choose certain things or search results based on criteria or keywords.
Narrowing down the presented material to only the things that match their search query helps visitors obtain pertinent information quickly.
We can quickly develop simple and complex web applications and projects using ReactJS since it smoothly integrates with other JavaScript libraries or frameworks.
To create a simple search filter application that performs searching for particular items, we will make a new React project for our app.
You can find a step-by-step approach to creating a React app on your machine here.
Once we have set up ReactJS on our systems and have the React app ready for execution, we will make three separate files for this project.
App.js
is a JavaScript file with the application's main component, and it defines the structure and functionality of the SearchBar component. The app will run the application upon execution.
SearchBar.css
is a Cascading Style Sheets (CSS) file used to define the visual appearance of the SearchBar component, such as setting colors, sizes, borders, and other styles for different elements.
SearchBar.js
is a JavaScript file with the application's main component, SearchBar, which is a reusable component that represents a search bar with dynamic filtering functionality. It lets users input a search query and instantly display a list of things matching it.
import React, { useState } from "react"; import "./SearchBar.css"; const SearchBar = () => { const [searchQuery, setSearchQuery] = useState(""); const [filteredItems, setFilteredItems] = useState([]); const itemList = [ { name: "Apple", price: "$1.99" }, { name: "Banana", price: "$0.99" }, { name: "Orange", price: "$1.49" }, { name: "Strawberry", price: "$2.49" }, { name: "Grapes", price: "$3.99" }, { name: "Watermelon", price: "$4.99" }, ]; const handleInputChange = (event) => { const query = event.target.value; setSearchQuery(query); const filtered = itemList.filter((item) => item.name.toLowerCase().includes(query.toLowerCase()) ); setFilteredItems(filtered); }; const handleSubmit = (event) => { event.preventDefault(); console.log("Search query:", searchQuery); const filtered = itemList.filter((item) => item.name.toLowerCase().includes(searchQuery.toLowerCase()) ); setFilteredItems(filtered); }; return ( <div> <form className="search-bar" onSubmit={handleSubmit}> <input type="text" placeholder="Search..." value={searchQuery} onChange={handleInputChange} /> <button type="submit">Search</button> </form> <ul className="item-list"> {searchQuery === "" ? ( itemList.map((item, index) => ( <li key={index}> {item.name} - {item.price} </li> )) ) : filteredItems.length > 0 ? ( filteredItems.map((item, index) => ( <li key={index}> {item.name} - {item.price} </li> )) ) : ( <li>No matching items found</li> )} </ul> </div> ); }; export default SearchBar;
Line 1–2: We import React and the useState
hook from React library and the SearchBar.css
file for styling purposes.
Line 4: In this line, We define a functional component called SearchBar
using an arrow function.
Line 5–6: In these lines, we use the useState
hook to declare two state variables: searchQuery
stores the current search query entered by the user and filteredItems
stores the list of items that match the search query.
Line 8–15: Here, we define an array called itemList
that represents a list of items with their names and prices.
Line 17–24: In these lines, we use handleInputChange
function that gets triggered whenever the input value changes. It extracts the query from the event target’s value and updates the searchQuery
state with it. It then filters the itemList
array based on the query, ignoring case sensitivity and updating the filteredItems
state with the filtered result.
Line 26–33: Similarly, we use handleSubmit
function that gets triggered when the form is submitted. It prevents the default form submission behavior. It logs the search query to the console. It performs the same filtering process as handleInputChange
to update the filteredItems
state based on the search query.
Line 35: In this line, we return the JSX markup of the component.
Line 37–45: These lines of code render a form with a search input field and a submit button. The value
attribute of the input field is set to searchQuery
, which ensures it reflects the current state value. The onChange
event of the input field is set to the handleInputChange
function, which updates the search query as the user types. The form’s onSubmit
event is set to the handleSubmit
function, which handles the form submission.
Line 46: Moving on, we have an unordered list (ul
) with a class of "item-list"
. The list is dynamically populated based on the search query and the state of filteredItems
.
Line 47–59: Here, we check if the search query is empty, then it displays all items from the itemList
array. However, if the search query is not empty and matches items are in filteredItems
, it then displays the filtered items.
Line 60: In this line, we check if the search query is not empty but has no matching items, then it displays a message saying, “No matching items found.”
Line 67: Finally, we export the SearchBar
component as the default export, making it available for other files to import and use by the file App.js
.
Upon execution of the above code, the output should look something like this:
We put "ap" in the search bar to check all list items containing one or both of the aforementioned characters. We see Apple and Grapes by writing our search query.
You can alter this according to your needs.
Free Resources