Filter Results with React
In my last post I discussed React’s controlled components and how you might set up a filter form. This week I’m going to show you how to setup the filter for the results.
Recap
Here’s what we built in the last post:
This component takes in a value from the user and assigns it to the poetFilter
within state
. Nothing special. What we’re focusing on in this post is what’s happening at line 15:
this.props.onChange(event.target.value)
The onChange
prop has been passed down from another component, a container component. As you’ve probably read in numerous other React posts, a container component is concerned with how things work, while a presentational component (i.e. the component above) is concerned with how things look.
The Container Component
So here’s the container:
Much of this you’ve probably seen before. You have a constructor
method in the VisiblePoets
class. This constructor method assigns state much like in the FilterForm
component. ComponentWillMount
is simply uploading poets after React decides whether or not the component can be mounted. But the most important method is the filterPoets
method at line 23.
This is the function passed in as the onChange
prop for the FilterForm
. Let’s go through this line by line.
We begin the function by assigning filteredPoets
all poets housed in this.state.poets
. If for instance you use Redux in the future, this would be all of the poets from the Redux store. Then we call filter
on these poets.
The filter
method iterates over the array and applies a returned expression to every element of the array. All elements that pass the expression will be returned in the array the filter
method constructs. In this case, we combine the first and last name of the poet into a string (ensuring that all letters are lowercased so our filter can be case sensitive). Then we return an expression.
The indexOf
method searches the array (or string, in this case) that it is called upon for whatever string is passed in and returns the index of position that element is located. If the method cannot find the search query anywhere, it returns -1
as the index. We only want poets that don’t return a -1
.
Once the filter is made, we setState
to the new array of poets, which calls a re-render the Poets
component.
Conclusion
And there you have it. With these two components, you can create a simple search filter that is even case sensitive. Until next time. Cheers!