Before you go, check out these stories!

Hackernoon logoHow to Build a Search Bar in React with React Hooks by@adebola

How to Build a Search Bar in React with React Hooks

Author profile picture

@adebolaAdebola Adeniran

I'm a full-stack developer with love for Ruby-on-Rails and React. Previously a student @microverse

Below is a small gif of what we will be building. A simple search box that allows us search through a contact list. We would be using functional components rather than class based components to achieve this.

Letโ€™s start!

Create a new react app using

npx create-react-app contacts-list

Then navigate into the contacts-list directory. Open the directory in your favorite code editor. In my case, Iโ€™m using vscode, so all I need to do from the command line is use:

code .

In your src directory, create a new folder called components and within that create a Numbers.js file.

Head over to your App.js file and import your Numbers.js component.

Next, we need to create a few persons that we would then pass down as props for our Numbers.js component to render.

Now, in our Numbers component, we would receive the props being passed down from App and use that to display the contacts list.

See the code below with explanations for each step added as comments.

Finally, we return the updated information from FilterDisplay each time itโ€™s updated.

If youโ€™re like me and would like to break out your Search bar into a separate component, then read on. Letโ€™s refactor this baby! Breaking out our search into a separate component would allow us use the same search bar in other components within our application.

First, we will create a Filter component, letโ€™s call this Filter.js inside our components folder. itโ€™ll take 2 props. Props for the input value and for an onChange event.

Next, we need to refactor our Numbers.js component so that all it does is to render the filtered persons list. Itโ€™ll accept one propโ€Šโ€”โ€Šthe list/array.

Recall that all our state is being managed within our App component and being passed down to our components as props.

Finally, in our App component, we will pass a stateful value to the input field in the Filter component, we would also pass a handleChange method that gets called when there is a change within the input field.

Within our return, our Numbers component will always check if the input field is blank. If itโ€™s, we render the original Persons array else we render the list based on whatโ€™s entered in the input field.

And thatโ€™s it, weโ€™re done!

Author profile picture

@adebolaAdebola Adeniran

Read my stories

I'm a full-stack developer with love for Ruby-on-Rails and React. Previously a student @microverse


Join Hacker Noon

Create your free account to unlock your custom reading experience.