AI Hints
Home›React Tutorial›TypeScript and Patterns
React · Lesson 63 of 120

Lists with Filters

A search box.

⏱ 2 min read▶ Video at 52:26🎓 Free
Watch this lesson in the React courseWatch on YouTube ↗Full React course

Filtering a list is one of the most common things in any app. Keep the filters in state, and derive the visible list from them, while rendering.

  • Very common
  • Filters in state
  • Derive the list

Search and type

Two pieces of state, the search text and the type. The shown list is derived from both, while rendering. No effects, and no extra state. We choose gear, and type the letter l. Run it.

App.jsxjsx
import { useState } from "react";
const PRODUCTS = [
  { name: "Trail 500", type: "bike" }, { name: "City 200", type: "bike" }, { name: "Volt 7", type: "bike" },
  { name: "Helmet", type: "gear" }, { name: "Lights", type: "gear" }, { name: "Lock", type: "gear" },
];
export default function App() {
  const [query, setQuery] = useState("");
  const [type, setType] = useState("all");
  const shown = PRODUCTS.filter(p =>
    (type === "all" || p.type === type) && p.name.toLowerCase().includes(query.toLowerCase()));
  return (<div>
    <input id="q" value={query} onChange={e => setQuery(e.target.value)} placeholder="Search" />
    <select id="t" value={type} onChange={e => setType(e.target.value)} style={{ fontSize: 19 }}>
      <option value="all">All</option><option value="bike">Bikes</option><option value="gear">Gear</option>
    </select>
    <ul>{shown.map(p => <li key={p.name}>{p.name}</li>)}</ul>
    {shown.length === 0 && <p>No matches</p>}
  </div>);
}
Also uses style.css
body{font-family:-apple-system,Helvetica,Arial,sans-serif;margin:22px;font-size:21px;color:#1d1d1f;background:#fafafa}
h1{font-size:34px;margin:0 0 14px} h2{font-size:26px;margin:0 0 10px}
button{font-size:19px;padding:9px 18px;border-radius:9px;border:0;background:#61dafb;color:#111;font-weight:600;margin:4px 6px 4px 0}
input{font-size:19px;padding:8px 10px;border:2px solid #bbb;border-radius:8px}
li{margin:5px 0} .box{padding:14px;border-radius:12px;background:#fff;border:2px solid #ddd;margin:8px 0}
.done{text-decoration:line-through;color:#999} small{color:crimson;display:block;font-size:16px} .big{font-size:64px;font-weight:800}
Also uses actions.json
[{"select": "#t", "value": "gear"}, {"type": "#q", "text": "l"}]

Summary

Keep filters in state, and derive the visible list while rendering. Next, sorting and tabs.

Key takeaways
  • query
  • type
  • Derived list
Next up: Sorting and Tabs — more UI state