Step 9: Live Search
Part of the Next.js Essentials section of Coddy's React journey — lesson 47 of 47.
Challenge
MediumFinish Coddy Eats with a live search.
- Create
app/api/dishes/route.jsexportingasync function GET()that awaitsgetDishes()and returnsResponse.json(dishes). - Create
components/SearchBox.jsxwith'use client';, holding aquerystring and amatchesarray in state. - Render
<input id="search-input" type="text">bound toquery. On change: with empty text, clear the matches; otherwisefetch('/api/dishes'),await response.json(), and keep the dishes whosenamecontains the text (case-insensitively). - Render
<ul id="search-results" className="reviews">with an<li>per match containing a<Link>withid={'match-' + dish.slug},href={'/menu/' + dish.slug}, and the emoji, a space, then the name. - Render
<SearchBox />inside the hero onapp/page.jsx.
Try it yourself
import Link from 'next/link';
import './globals.css';
export const metadata = {
title: {
default: 'Coddy Eats',
template: '%s | Coddy Eats',
},
};
export default function RootLayout({ children }) {
return (
<html lang="en">
<body>
<nav className="nav">
<Link className="brand" href="/">Coddy Eats</Link>
<Link id="nav-menu" href="/">Menu</Link>
<Link id="nav-desserts" href="/?category=dessert">Desserts</Link>
</nav>
<div className="container">
{children}
</div>
</body>
</html>
);
}