Search Bar Filter in React JS with API

Arhaan Ali
5 min readAug 12, 2024

--

Hey everybody, Let’s look at how to make a Search Bar Filter in React JS with API there are many sites using that feature inside the application, users will able to search for something inside the search bar and who can see the search suggestions. Building a search bar in a React JS utility is always quite normal.

It enables the customers to find specific information within a short period. When integrated with an API, a search bar is ready to kind and filter knowledge from a database in real-time on the idea of consumer entry.

Understanding the Fundamentals
React JS is a well-liked JavaScript library for constructing personal interfaces. It’s component-based, meaning every part of the person interface is broken down into small, reusable items referred to as parts. A search bar is usually one such element.

APIs (Utility Programming Interfaces) are used to allow two or more completely different software program methods to hook up with each other. In this regard, the API provides information that can be searched by using a bar.

Search Bar Filter in React JS with API

before moving the codes, you should watch the tutorial that I made, I know video is a better way to understand everything step by step from scratch. So, I’m going to share with you the video tutorial below.

please watch the video till to end, once you’ve seen the complete tutorial hope you’ve learned many new things and tactics that are used inside the project in React JS. Let’s see the codes that are used to build a Search Bar Filter in React JS.

You May Also Like:

First of All, you need to build a project in React JS using vite, once you have done it, then you need to clean the codes means removing all the built-in codes that are written default inside the file. Once you have done that then you need to use below mentioned codes on App.jsx file

import React from "react";
import SearchBar from "./components/SearchBar";
function App() {
return <SearchBar />;
}
export default App;

Inside the App.jsx has the single component you need to make another file with the name of Searchbar.jsx and write the same name, and then you need to use the below-mentioned codes on the search bar.

import React, { useEffect, useState } from "react";
import InputControl from "./InputControl";
import SearchFilter from "./SearchFilter";

function SearchBar() {
const [ApiData, setAPIData] = useState([]);
const [searchItem, setSearchItem] = useState("");
const [filteredData, setfilteredData] = useState([]);
const [isloading, setLoading] = useState(true);
const [isError, setError] = useState(null);
// get the Data From API
useEffect(function () {
fetch("https://dummyjson.com/posts")
.then((response) => response.json())
.then((data) => {
setAPIData(data.posts);
setfilteredData(data.posts);
})
.catch((err) => {
console.log(err);
setError(err);
})
.finally(() => {
setLoading(false);
});
}, []);
// input Change Envet
const handleInputChange = (e) => {
const SearchTerm = e.target.value;
setSearchItem(SearchTerm);
//Filter Data
const filterItems = ApiData.filter((data) =>
data.title.toLowerCase().includes(SearchTerm.toLowerCase()),
);
setfilteredData(filterItems);
};
return (
<div className="container">
<div className="wrapper">
<form>
<div className="form_control">
<InputControl
handleInput={handleInputChange}
searchItem={searchItem}
/>
{isloading && <p>Loading..............</p>}
{isError && <p>There was an Error</p>}
{!isloading && !isError && filteredData.length === 0 ? (
<p>No Data Found</p>
) : (
searchItem && (
<div className="list_item">
<SearchFilter
filtereddata={filteredData}
handleClick={setSearchItem}
/>
</div>
)
)}
</div>
<button className="btn_search">Search</button>
</form>
</div>
</div>
);
}
export default SearchBar;

After that, you need to do a few things such as create an InputControl component and also SearchFilter components. When you control the input, then use blow mentioned codes that are used to handle the input field.

import React from "react";
function InputControl({ handleInput, searchItem }) {
return (
<input
type="text"
className="input-file"
placeholder="Search...."
onChange={handleInput}
value={searchItem}
/>
);
}
export default InputControl;

The last thing you need to make is a SearchFilter component that is used to display the search result from the API and display it inside the drop list items. So, you need to use those codes.

import React from "react";

function SearchFilter({ filtereddata, handleClick }) {
return (
<ul>
{filtereddata.map((posts) => (
<li key={posts.id} onClick={() => handleClick(posts.title)}>
{posts.title}
</li>
))}
</ul>
);
}
export default SearchFilter;

I’ve used CSS to design the project, let’s see the codes that are used to design the project using CSS.

@import url("https://fonts.googleapis.com/css2?family=Poppins:ital,wght@0,100;0,200;0,300;0,400;0,500;0,600;0,700;0,800;0,900;1,100;1,200;1,300;1,400;1,500;1,600;1,700;1,800;1,900&display=swap");

* {
padding: 0;
margin: 0;
box-sizing: border-box;
}
body {
background-color: #444dac;
display: flex;
justify-content: center;
align-items: center;
min-height: 100vh;
font-family: "poppins", sans-serif;
}
.wrapper {
width: 500px;
}
form {
position: relative;
}
form input {
width: 100%;
outline: none;
border: none;
font-family: inherit;
padding: 1rem 1rem;
font-size: 1rem;
box-shadow: 0 0 5px rgba(0, 0, 0, 0.5);
border-radius: 5px;
}
form button {
position: absolute;
top: 0;
right: 0;
outline: none;
border: none;
font-family: inherit;
padding: 1rem 1rem;
font-size: 1rem;
border-radius: 5px;
cursor: pointer;
}
form button:hover {
transform: scale(0.98);
}
.list_item {
background-color: #fff;
z-index: -1;
height: 250px;
overflow: hidden;
overflow-y: auto;
}
.list_item ul {
list-style-type: none;
}
.list_item ul li {
padding: 1rem 1rem;
border-bottom: 1px solid #ddd;
}
.list_item ul li:hover {
background-color: #ddd;
cursor: pointer;
}

How the Search Bar Works
The search bar is an easy entry discipline that allows customers to sort their queries. When the person varieties, the search bar sends a request to the API. The API responds with knowledge that matches the search question.

Setting Up the Search Bar
To create a search bar, you first must design the enter discipline. This enter discipline will seize what the person varieties. The captured textual content is then used to filter the info.

Connecting to the API
After that, it is possible to append the search bar to an API. Signed API may be exterior (as for example public database) or internal (from your server for example). The moment connected, the search bar passes on the person’s question to the API.

Dealing with API Responses
When the API receives the search question, it processes the request and returns related knowledge. This knowledge is perhaps an inventory of things, names, or any data the API supplies. The React utility will then show this filtered knowledge to the person.

Filtering Information
Filtering is an important thing a part of the search bar. Because the person varieties, the search bar repeatedly sends the up-to-date textual content to the API. The API responds with knowledge that matches the present textual content. For instance, in the event you sort “apple,” the API would possibly return an inventory of apple varieties.

Updating the Show
Because the API returns knowledge, the React element updates the show. Solely the objects that match the search question are proven. This makes the search characteristic dynamic and responsive.

Conclusion
A search bar filter in React JS with an API is among the best software for developing functions that the consumer will in a position to work together with. If the method is divided into small steps, it is possible to combine a search characteristic that improves the experience of the individual. Whether it is targeted at filtering the merchandise in an internet retailer or the process of finding specific information in a database, the search bar is an essential element of most modern web applications.

--

--

Arhaan Ali

I’m Developer and Blogger I’ve been sharing my personal expereince on Udemy, YouTube and Also Personal Website.