Build a search bar in React

  • 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.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Aiden Oliver

Aiden Oliver

An aspiring software developer, hacking enthusiast, and competitive gamer.