Search Filter with React Hooks

Mike Archer
2 min readFeb 21, 2021

--

One common component to find in many react projects is a search bar. This can be implemented a number of ways, whether it be as a standard search that renders information when submitted, or more of a filter style, where the items on the page re-render as the filter is typed and applied. In this blog I want to walk you through set up of a basic searching function, using react hooks.

In our example, we are fetching our data that is a list of student names. We want to use a searchable field to filter out students from our list.

The first thing we do after creating our functional component, is to set up our state. Using hooks, this means creating our students (array of all student names), as well as our searchTerm (string we are searching for) pieces of state. Students will have an initial value of ‘[]’, with searchTerm being “‘’”.

Next, we fetch our data using useEffect, note the empty square brackets as the last argument, this ensures we do not get stuck in an infinite loop of rendering. Once the data is fetched, we assign it to our ‘students’ state using the custom hook we made.

Our handleChange helper method is one of the most important parts here. By setting this to the “onChange” of our input, this is how we can cause the list of students to re-render and change as we search, rather than requiring a submit. As the value inside the input changes, we are using our ‘setSearchterm’ to adjust the ‘searchTerm’ piece of state. Remember, every time state changes, this component will re-render.

When we render our students, in order for our filter to work we add an additional step. Rather than just calling .map on the array, we first call .filter() to go through each student, and in this case find students where the name property includes our search term.

This is not the only way to perform tasks such as this, but this is a great template that can scale easily with more complex data structures or additional filtering and searching.

--

--

No responses yet