DEV Community

Mikeu28
Mikeu28

Posted on

Using .filter in React

While learning coding in my bootcamp, I found myself stumped by the way .filter works. This blog is both reinforcement of my own learning and will hopefully help prevent someone else from falling into the same holes that I did.

To set up a proper filter in react; first we need state.
Image description

Using an event handler such as onChange or onSubmit, we update the states search value with the data we are looking for.

Image description
Image description

With the event handler in place, we can now create a variable that will house the data we are filtering for.
Image description

Here, we ensure that we make a copy of our form data as to not accidentally manipulate it permanently in some way. Filter is then written the same way you would write .map as well.

Once we have our data we simply update what react displays.

Image description

React should now display either all the data or what the filtered results show. If nothing matches the search, react will show nothing.

Top comments (0)