Write previous and next links for the teas layout, with arrow-key shortcuts
The teas section's layout shows a stepper above every tea's page: links to the teas before and after the current one, in the shop's order. The layout sits above [slug], so its own params don't include the slug, and it renders the stepper with no props:
app/teas/layout.tsximport TeaStepper from "./tea-stepper";
export default function TeasLayout({ children }: LayoutProps<"/teas">) {
return (
<>
<TeaStepper />
{children}
</>
);
}
Write the stepper, app/teas/tea-stepper.tsx, whose default export is TeaStepper. Read the current tea's slug with useParams(), and find it in teas from @/lib/teas. Render a <nav aria-label="Tea stepper"> with a next/link Link to the tea before, Previous: Green tea, and one to the tea after, Next: Oolong tea, each to /teas/<slug>. Leave out Previous on the first tea and Next on the last. Render nothing where there's no tea, like /teas itself, or a slug the shop doesn't sell.
The arrow keys step too: ArrowLeft goes to the tea before and ArrowRight to the tea after, with router.push. Listen on window, and stop listening when the stepper unmounts. Ignore a key when there's no tea that way; when Alt, Ctrl, Meta, or Shift is held (Alt with an arrow is Back or Forward in many browsers); when it was pressed in an input, a textarea, a select, or a contentEditable element; and when something already handled it (event.defaultPrevented).
app/teas/tea-stepper.tsx"use client";
import Link from "next/link";
import { useParams, useRouter } from "next/navigation";
import { teas } from "@/lib/teas";
export default function TeaStepper() {
const { slug } = useParams<{ slug?: string }>();
const index = teas.findIndex((tea) => tea.slug === slug);
const previous = teas[index - 1];
const next = teas[index + 1];
return (
<nav aria-label="Tea stepper">
<Link href={`/teas/${previous.slug}`}>Previous: {previous.name}</Link>
<Link href={`/teas/${next.slug}`}>Next: {next.name}</Link>
</nav>
);
}
lib/teas.ts (read-only)export type Tea = { slug: string; name: string };
/** The shop's teas, in the order the stepper walks through them. */
export const teas: Tea[] = [
{ slug: "green", name: "Green tea" },
{ slug: "mint", name: "Mint tea" },
{ slug: "oolong", name: "Oolong tea" },
];
- links to the teas on either side of the current one
- has no Previous on the first tea and no Next on the last
- renders nothing without a tea the shop sells
- steps with the arrow keys through router.push, only where there's a tea
- ignores arrow keys with a modifier, in a text field, or already handled
- keeps up when the visitor moves to another tea
- stops listening when it unmounts
- follows its links with next/link
The answer
Write it yourself first. Then compare it with a reference solution and the checks it passes.
Checking your sign-in…