How to Filter Search Results While Typing With React

Search bars are a great way to help users find what they need on your site. They’re also good for analytics if you’re tracking what your visitors are searching for.


You can use React to create a search bar that filters and displays data as the user types. With react hooks and the JavaScript map and filter array methods, the end result is a responsive, functional search box.


The search takes input from a user and triggers the filter function. You can use a library like Formik to create forms in React, but you can also create a search bar from scratch.

If you don’t have a React project and want to contribute, create one using the create-react-app command.

npx create-react-app search-bar

In which app.js File, add the form element including the input tag:

export default function App() {
return (
<div>
<form>
<input type="search"/>
</form>
</div>
)
}

You should use those useState Respond hook and die upon change Event to control input. So import useState and change the input to use the state value:

import { useState } from "React"
export default function App() {
const [query, setquery] = useState('')
const handleChange = (e) => {
setquery(e.target.value)
}
return (
<div>
<form>
<input type="search" value={query} onChange={handleChange}/>
</form>
</div>
)
}

Every time a user types something into the input element, handleChange updates the status.

Filtering the data when the input changes

The search bar should trigger a search using the user-provided query. That means you should filter the data inside the handleChange function. You should also track the filtered data in Status.

First change the status to include the data:

const [state, setstate] = useState({
query: '',
list: []
})

Bundling the stats in this way, rather than creating one for each stat, reduces the number of renders and improves performance.

The data you filter can be any data you want to search. For example, you can create a list of sample blog posts like this:

const posts = [
{
url: '',
tags: ['react', 'blog'],
title: 'How to create a react search bar',
},
{
url:'',
tags: ['node','express'],
title: 'How to mock api data in Node',
},
]

You can also retrieve the data from a CDN or database via an API.

Next, modify the handleChange() function to filter the data as the user types into the input.

const handleChange = (e) => {
const results = posts.filter(post => {
if (e.target.value === "") return posts
return post.title.toLowerCase().includes(e.target.value.toLowerCase())
})
setstate({
query: e.target.value,
list: results
})
}

The function returns the posts without searching them if the query is empty. When a user enters a search query, it verifies that the post title contains the search query text. Converting the post title and query to lower case ensures that the comparison is case insensitive.

Once the filter method returns the results, the handleChange function updates the status with the query text and the filtered data.

Viewing the search results

Displaying the search results involves iterating through the list array using Map method and display the data for each item.

export default function App() {
return (
<div>
<form>
<input onChange={handleChange} value={state.query} type="search"/>
</form>
<ul>
{(state.query === '' ? "" : state.list.map(post => {
return <li key={post.title}>{post.title}</li>
}))}
</ul>
</div>
)
}

Within the ul tag, the component checks whether the query is empty. If this is the case, an empty string will be displayed, as this means that the user has not searched for anything. If you want to search a list of items that you are already viewing, uncheck this box.

If the query is not empty, the map method iterates through the search results and lists the post titles.

You can also add a check mark that displays a helpful message if the search returns no results.

<ul>
{(state.query === '' ? "No posts match the query" : !state.list.length ? "Your query did not return any results" : state.list.map(post => {
return <li key={post.title}>{post.title}</li>
}))}
</ul>

Adding this message improves the user experience as the user doesn’t have to look at an empty field.

Handling more than one search parameter

You can use React states and hooks along with JavaScript events to create a custom search element that filters an array of data.

The filter function only checks if the query matches a property – title – in the objects within the array. You can improve the search functionality by using the logical OR operator to match the query against other properties in the object.

Leave a Reply

Your email address will not be published. Required fields are marked *