Search box for the live inventory list
React · React · intermediate · greenfield
Adds client-side search to the inventory list. Keeps the query and the filtered results in component state and recomputes the results on every keystroke with a case-insensitive match. Typing narrows the list instantly and clearing the box brings everything back.
The parent polls /inventory every 30 seconds and passes a fresh `products` array down; stock levels change while the page is open.
Requirements
- Add a search box that filters the product list by name as the user types.
- Matching is case-insensitive.
- The list must stay in sync with the `products` prop as it updates — stock changes from the poll must show up.
Files touched
- src/components/InventorySearch.jsx
--- src/components/InventorySearch.jsx
+import { useState } from 'react';
+
+export function InventorySearch({ products }) {
+ const [query, setQuery] = useState('');
+ const [filtered, setFiltered] = useState(products);
+
+ function handleQueryChange(event) {
+ const next = event.target.value;
+ setQuery(next);
+ setFiltered(
+ products.filter((product) =>
+ product.name.toLowerCase().includes(next.toLowerCase())
+ )
+ );
+ }
+
+ return (
+ <div className="inventory-search">
+ <input
+ type="search"
+ aria-label="Filter products"
+ placeholder="Filter products…"
+ value={query}
+ onChange={handleQueryChange}
+ />
+ <ul>
+ {filtered.map((product) => (
+ <li key={product.id}>
+ {product.name} · {product.stock} in stock