React: Search Component

Adam James
3 min readSep 24, 2021

While I was building out my final React project for Flatiron School, I had a list of features that sat under a “might get to eventually but not the end of the world if I don’t get to them before the due date” list. These were mostly generic features that didn’t help me meet any of the project requirements, but would have been fun to implement if I had the chance to. One of the features on that list was a filter or search bar that would let a user filter through the data and remove all of the information that doesn’t meet the filtered requirement from the page.

The first step is to create a new component for the search input field. This component isn’t going to be very complicated, it’s just an input tag that’s being passed an input change function via props from the component it’s mounted to (in my case, the Employee Container component).

Search Component

In my EmployeesContainer component, where I’m placing the search field, I want to create a new piece of state to save the search criteria that’s typed into the input field.

State in EmployeesContainer

This search criteria starts as an empty string, and is changed using the handleInputChange function, which sets the state as letters are typed into the field. This function is passed via props into the Search component.

handleInputChange function

Once the ability to set a searched string is finished, I filtered the employees that were being mounted on the page. I created a new variable of filteredEmployees. This variable was set to a ternary operator. If nothing has been typed into the input, then the employees displayed on the page will be the entire portion of employees saved in the store. However, if search is longer than 0, the variable will be saved to a filtered set of employees. This filter checks to see if each employee name includes the search term.

filteredEmployees variable

The last two things I had to do were simple. First, I had to mount the Search component on the Employee Container with the handleInputChange function passed in as a prop. Second, I had to switch the map function on line 63. Originally, I had the function running on all employees. Now, I wanted to run it on the filtered employees variable. After those simple additions, I had a completely functional search component!

Completed EmployeesContainer with Search Component