Implementing a Search Bar Feature in React

Sam Hall
3 min readMar 25, 2021

Search bar features are a useful graphical widget common to user interface development. They are also fairly simple to implement via React when building an application. Here is a simple search feature that retrieves a name from an array of names based on the search query value, returns that filtered element and renders it on the DOM.

Import {useState} and set state variables

First import {useState} from React at the top of your App component. Search bar functionality calls for setting a state variable that changes based on the input value of the bar.

Import {useState} and set state variables.

Here, I’ve created the state variable “searchQuery” whose initial value is an empty string. I’ve also created a state variable “filteredName” for the name element we want to return and render on the DOM based on our search. I’ve also included the name array we’ll be iterating over based on the searchQuery, and rendered it as an Unordered List on the DOM as seen above.

Define a callback function and pass it down as a prop

The purpose of the function “handleSearch” is to retrieve a value from our search component and set our state variable “searchQuery” to the input value of the search bar. I’ve also included logic within this function that maps over every string element in the “people” array, inquires if that element includes the value set in our search bar, and then sets our state variable “filteredName” to that element, a single name, which will be returned in red as seen in the example above.

Set a callback function and pass it down as a prop to the Search Component within App.

Pass the callback function down to the child Search component as a prop. After doing so, the input value within the Search Component can be assigned to “searchQuery.”

Set an “onChange” event handler on the input field

Within the child Search Component, set an “onChange” event handler on the input field (the search bar, itself). The purpose of the “onChange” event in react is detecting when a change is made in an input field.

(Console.log( to see the characters logged as you type them within the search bar!) is transferred up to the App component’s “handleSearch” function and passed as an argument into the function — the parameter “newSearchQuery”.

That should be all it takes! Here is a demo of the desired search functionality:

Our desired search bar functionality.