Introduction
When narrowing down data by switching multiple conditions in React, I often struggled with how to combine useState and filter().
Here, I've re-organized it with a simple example to make the mechanism clear at a glance.
Implementation Goal
Imagine using a button to toggle the state (true/false) and display only the data that matches the selected condition.
Sample code
import { useState } from "react";
export default function App() {
const [filters, setFilters] = useState({ wifi: false, power: false, voice: false });
const toggle = (key) => setFilters({ ...filters, [key]: !filters[key] });
const data = [
{ id: 1, wifi: true, power: true, voice: false },
{ id: 2, wifi: false, power: true, voice: true },
{ id: 3, wifi: true, power: false, voice: true },
];
const result = data.filter((d) => {
if (filters.wifi && !d.wifi) return false;
if (filters.power && !d.power) return false;
if (filters.voice && !d.voice) return false;
return true;
});
return (
<div>
{["wifi", "power", "voice"].map((key) => (
<button key={key} onClick={() => toggle(key)}>
{key}: {filters[key] ? "ON" : "OFF"}
</button>
))}
<ul>
{result.map((r) => (
<li key={r.id}>Item {r.id}</li>
))}
</ul>
</div>
);
}
Lessons Learned, Summary
1️.useState Allows for Consolidated Management
By managing multiple conditions (wifi, power, voice) in a single object, you can neatly organize your state.
The toggle function is a "wrapper function."
Instead of using setFilters directly, you can explicitly specify which keys to toggle and safely update them.Flexible filtering with filter()
If you want to add more conditions, just add an if line.
Top comments (0)