Filter the project list as the user types

React · React · advanced · greenfield

Adds live filtering to the project list. Keeps the query in state and derives the visible projects from the prop and the query on each render, memoized so large lists don't re-filter needlessly. Matching is case-insensitive.

Sidebar of the workspace view; some workspaces have a few hundred projects.

Requirements

Files touched

--- src/components/ProjectFilter.jsx
+import { useMemo, useState } from 'react';
+
+export function ProjectFilter({ projects }) {
+  const [query, setQuery] = useState('');
+
+  const visible = useMemo(() => {
+    const q = query.toLowerCase();
+    if (!q) return projects;
+    return projects.filter((p) => p.name.toLowerCase().includes(q));
+  }, [projects, query]);
+
+  return (
+    <div>
+      <input
+        value={query}
+        onChange={(e) => setQuery(e.target.value)}
+        placeholder="Filter projects…"
+      />
+      <ul>
+        {visible.map((p) => (
+          <li key={p.id}>{p.name}</li>
+        ))}
+      </ul>
+    </div>
+  );
+}

Review this PR

React practice