Write a NavLink that marks itself when it points to the current page or its section
Every menu in Leaf and Kettle is built from one component, NavLink, so they all show the visitor where they are in the same way. Write it in app/components/nav-link.tsx as the default export. It takes the props a next/link Link takes, with href as a string, plus exact, and renders a Link with all of them except exact.
Mark it by the current path. On the link's own page, give it aria-current="page". On a page inside its section, like /teas/green for a link to /teas, give it aria-current="true". Only whole segments count, so /teaspoons isn't inside /teas. A link with exact is only marked on its own page, and a link to / only ever is. A marked link also gets the class active, added to any className it was given; an unmarked one keeps its className as it is.
Layouts are Server Components, and they render the menus, so make sure a layout can render NavLink.
// On /teas/green:
const teas = <NavLink href="/teas" className="menu-link">Teas</NavLink>;
// renders <a href="/teas" class="menu-link active" aria-current="true">Teas</a>
const allTeas = <NavLink href="/teas" exact>All teas</NavLink>;
// renders <a href="/teas">All teas</a>
app/components/nav-link.tsximport Link from "next/link";
import { usePathname } from "next/navigation";
type NavLinkProps = React.ComponentProps<typeof Link> & { href: string; exact?: boolean };
export default function NavLink({ href, exact = false, className, ...rest }: NavLinkProps) {
return <Link href={href} className={className} {...rest} />;
}
- marks the link to the page you're on
- marks a section's link on the pages inside it, by whole segments, whatever the query
- marks an exact link and a link to / only on their own page
- adds active to the className it's given, and leaves it alone when unmarked
- passes the other props on to Link, and moves its mark when you follow it
- is a Client Component, so a Server Component layout can render it
The answer
Write it yourself first. Then compare it with a reference solution and the checks it passes.
Checking your sign-in…