Introduction
When creating a filter function in React, I found myself stuck, unsure of how to filter data based on multiple criteria.
Here, I'd like to re-organize my thinking.
Problem
When creating a filter function for a map app in React, I found myself stuck, unsure of how to filter data based on multiple criteria.
I could toggle between conditions by pressing buttons like "WiFi," "Power," and "Voice Enabled," but I couldn't imagine how to keep only spots that met those criteria on the map.
I struggled with figuring out when and what logic to use to hide pins that didn't meet the criteria.
The Solution
After some research, I realized that using the .filter() method, which handles arrays, could simply filter out data that didn't meet the criteria.
const filtered = spots.filter((spot) => {
if (filters.wifi && !spot.wifi) return false;
if (filters.power && !spot.power) return false;
return true;
});
What I learned
.filter() is simple enough: "filter out data that doesn't meet the conditions."
The same concept can be applied regardless of where the data comes from, such as Supabase or Google Maps.
.filter() may seem unimpressive at first glance, but it's a basic technique that can be used in any situation where you want to "change the display depending on conditions" in React.
The idea of "excluding data that doesn't meet the conditions" was key to understanding it.
Top comments (0)