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
- Show a text box that filters the project list by name as the user types.
- Matching is case-insensitive substring match.
- The filtered list must always reflect the current projects prop and the current query.
Files touched
- src/components/ProjectFilter.jsx
--- 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>
+ );
+}