How to filter search results when typing with React

Search bars are a great way to help users find what they need on your website. They are also useful for analytics if you keep track of what your visitors are looking for.


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


The search will take a user’s input and trigger 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 follow along, create one using the create-react-app command.

npx create-react-app search-bar

In the 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 the useState The React hook and the about the change event to control the input. So, import useState and modify 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>
)
}

Whenever a user types something inside the input element, handleChange updates the state.

Filtering data when changing input

The search bar should trigger a search using the query provided by the user. This means you have to filter the data inside the handleChange function. You should also track filtered data in the report.

First, modify the state to include the data:

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

Grouping state values ​​in this way, instead of creating one for each value, reduces the number of renders, thus improving performance.

The data you are filtering can be anything you want to search on. 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 using an API from a CDN or from a database.

Next, modify the handleChange() function to filter data each time the user types in 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 messages without iterating through them if the query is empty. If a user entered a query, it checks whether the message title includes the query text. Converting the post title and query to lowercase ensures that the comparison is case-insensitive.

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

Viewing search results

Displaying search results involves looping over the list array using the 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>
)
}

Inside the ul tag, the component checks if the request is empty. If so, it displays an empty string because that means the user didn’t search for anything. If you want to search through a list of items you are already viewing, uncheck this box.

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

You can also add a checkmark 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 because the user is not left with an empty space.

Managing multiple search parameters

You can use React state 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 inside the array. You can improve the search functionality by using the logical OR operator to match the query to other properties of the object.

Amanda J. Marsh