How to build a search box in React with hooks.
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.
Update 1: In the handleChange metthod, remove the .toLowerCase() on the name when we’re returning the object because this modifies the name format in the original array.
Add the .toLowerCase() method to the filter for the names so you have something like
newList = oldList.filter(person =>
person.name.toLowerCase().includes(word.toLowerCase())
);
And that’s it, we’re done!
See the repo on github.