How to filter search results while typing with React

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


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


The search will take input from a user and trigger the filtering feature. 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 proceed, create one using the create-react-app command.

npx create-react-app search-bar

In the Application.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 reaction hook and onChange event to control input. So, import useState and modify the input to use the value of the state:

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 inside the input element, handleChange update the status.

Filter data on input change

The search bar should trigger a search using the query the user provides. This means that you must filter the data within the handleChange function. You should also keep track of the leaked data in the state.

First, modify the state to include the data:

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

Grouping state values ​​in this way, rather than creating one for each value, reduces the number of renders and improves performance.

The data you filter 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 get the data using an API from a CDN or database.

Next, modify the handleChange() function to filter the data whenever 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 looking for them if the query is empty. If a user has typed a query, check if the post title includes the query text. Converting the post title and query to lowercase ensures that the comparison is not case sensitive.

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

Show search results

Displaying the search results involves looping through the list array using the Map method and displaying the data of each element.

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 query is empty. If so, it returns an empty string because it means the user hasn’t searched for anything. If you want to search a list of items that you are already displaying, remove this check.

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

You can also add a flag 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 staring at a blank space.

Handling more than once the search parameter

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) on the objects within the array. You can enhance the search function by using the logical OR operator to match the query with other properties of the object.

See also  Thomson Reuters Corporate Global Trade Survey Report: Turbulence tempered by technology

Leave a Comment