Create a Search Filter in React from Scratch ๐
Learn to create search filter in React ๐
Hello Folks ๐
This is Savio here. I'm young dev with an intention to enhance as a successful web developer. I love building web apps with React. I have proved my superiority in frontend technologies.
Today, Let's learn how you can create a well-efficient search filter in React โ๏ธ. So, let's start!
Create React App
First of all, we first have to create a react app. You know it!
npx create-react-app search-filter-app
This will create you a normal react app. You can start the server by npm start
. Now, let's have a look at our folder structure ๐ฅ Make sure, you have this files ready ๐ค
Lets start with App.js
, we can use https://jsonplaceholder.typicode.com/ API, to get some fake posts data. First, lets create a useState
hook ๐
const [data, setData] = useState([]);
Now, lets create a useEffect
with no dependency that should load only once. ๐ช
useEffect(() => {
fetch("https://jsonplaceholder.typicode.com/posts")
.then((response) => response.json())
.then((json) => setData(json));
}, []);
Now, lets render our app, we just need an input
that acts as our search bar and then, lets map through the data โ๏ธ
<div className="App">
<input type="text" placeholder="Search name" />
{data.map((post, key) => {
return (
<p className="blog" key={key}>
{post.title}
</p>
);
})}
</div>
Now, lets next step is to handle the search, for that, I'm setting a new useState
hook called searchTerm
๐ป
const [searchTerm, setSearchTerm] = useState("");
And now, lets handle the onChange
event of our input
๐
<input type="text" placeholder="Search name" value={searchTerm} onChange={(e)=> setSearchTerm(e.target.value)}
/>
And lastly, lets create a small logic of handling the search, lets use filter
for it, we're first converting it to toLowerCase()
and then check if it is same as searchTerm
, and then map through it. Lets see how I made it work ๐
{
data
.filter((val) => {
if (searchTerm === "") {
return val;
} else if (
val.title.toLowerCase().includes(searchTerm.toLowerCase())
) {
return val;
}
})
.map((post, key) => {
return (
<p className="blog" key={key}>
{post.title}
</p>
);
})
}
}
that's it ๐, you made it work, it works just fine, lets add some css
to make it better ๐ Add this to App.css
input {
padding: 10px;
border: 1px solid #111;
width: -webkit-fill-available;
border-radius: 5px;
}
.blog {
padding: 10px;
border: 1px solid #ccc;
border-radius: 5px;
}
Now, everything is over, time to test it, Here it goes, it works like a charm ๐ Congrats ๐ฅณ
๐ Wrapping Up
Yeah, that's a wrap. Hope you enjoyed the article. Do not hesitate to share your feedback. I am on Twitter @saviomartin7. Give a follow!
Follow me on Github @saviomartin, Don't miss my amazing projects! ๐ฏ
Feedbacks are greatly appreciated! ๐ Have an amazing day!
๐ Lets connect
๐ Support
If you're enjoying my blog, consider buying me a coffee โ๏ธ, it will help me a lot!