Build a search bar in React
In this guide I am going to walk through how to make a search bar using React Hooks. There are a couple ways to do it, however the most commonly used and effective way I found to do it is by searching through an array of objects.
If you’ve seen my other posts, you’ll see that I use a similar method to include our input into the search bar.
Step 1: Create an array of objects with the useState hook
Step 2: Create a string value and array using the useState hook again and set them to empty.
- Create a function that will handle the changes in the input field. We will add the input field into the return statement later. We will pass in an event argument.
- Inside the body of our function we will update our string value with our event argument we passed in.
- Next, we will create a variable that will map over each of our object elements in the array using and return the key values for each element. In our mapping function we will pass in an argument that will represent each object essentially and return the key-values of each object using item as the key and binding the keys to it.
- After that, we will create an if statement. For the condition, we will say that if the string value is not empty, run some code.
- Inside this the body of the if statement, create a variable with an empty array. This will be our new, filtered data.
- After that, set the empty array variable to the variable that maps over our original data array. Pass in the filter binding and pass in an argument. This argument will filter through our data and return an item key as long as our string matches it and then update our empty useState array with the new filtered variable. If it does not match, we will update the array with the existing, unfiltered data.
- Now we will add our JSX. I made separate files for Input and Data and added them like so, but can actually just leave all the JSX in this file if you want. For now, I’ve added this JSX code that accepts our string value and our handleChange function to check for any changes.
- The data value will display the original array of data if our string value is less than one and if our string value is greater than one it will show the updated array called searchResults. In the next step we will create those files.
- Create a file called Input.js and pass in an object with an argument of value and handleChange. We will be passing in our string value and handleChange function.
- Now create a Data file that accepts an object with an argument called data.
- We will map through this data since we will be passing in an array as our argument.
Let me know if this example helped.