usePathname() returns the current path, such as /about. The navigation
marks the matching link with aria-current="page", which screen readers announce
as "current page", and the CSS makes it bold. The navigation is in the layout,
so it stays mounted and updates as the path changes.
Changing the URL
SearchBox writes what you type into the query string:
useSearchParams() reads the current query string. Copying it into a
URLSearchParams keeps any other values that are already there.
useRouter() gives you router.push(url) and router.replace(url), the
code versions of following a link.
The page, a server component, reads q from searchParams and filters. The
search box doesn't need to know how. Because a reader could repeat the key
(?q=a&q=b, from the last lesson's Going further), the page picks one value
before calling toLowerCase:
push adds a history entry, like following a link. replace swaps the current
one. Typing calls replace, so the back button skips over every keystroke and
goes straight back to the previous page.
Predict
Type comp, then press the address bar's back button. Where do you land?
Check your prediction
On the page before Topics, such as About, not on /?q=com. replace added no
entries.
Exercise
Surprise me
Add a Surprise me button to the Topics page that goes to a random topic,
and adds a history entry, so back returns to the list.
Your working spaceNext.js · 8 filesimport NavLinks from "./NavLinks.jsx";
import "./globals.css";
export default function RootLayout({ children }) {
return (
<html lang="en">
<body>
<header>
<NavLinks />
</header>
{children}
</body>
</html>
);
}
import Link from "next/link";
import { getTopics } from "@/lib/topics.js";
import SearchBox from "./SearchBox.jsx";
export default async function HomePage({ searchParams }) {
const { q } = await searchParams;
// ?q=a&q=b gives an array: use the first value. No q at all gives "".
const query = Array.isArray(q) ? q[0] : (q ?? "");
const topics = await getTopics();
const shown = topics.filter((topic) => topic.title.toLowerCase().includes(query.toLowerCase()));
return (
<main>
<h1>Topics</h1>
<SearchBox />
<ul>
{shown.map((topic) => (
<li key={topic.slug}>
<Link href={`/topics/${topic.slug}`}>{topic.title}</Link>
</li>
))}
</ul>
<p className="muted">{shown.length} of {topics.length} topics</p>
</main>
);
}
"use client";
import Link from "next/link";
import { usePathname } from "next/navigation";
const links = [
{ href: "/", label: "Topics" },
{ href: "/about", label: "About" },
];
// usePathname() is the current path, such as "/about". Client components only.
export default function NavLinks() {
const pathname = usePathname();
return (
<nav>
{links.map((link) => (
<Link key={link.href} href={link.href} aria-current={pathname === link.href ? "page" : undefined}>
{link.label}
</Link>
))}
</nav>
);
}
"use client";
import { usePathname, useRouter, useSearchParams } from "next/navigation";
// Typing writes the search into the URL: /?q=rout. The server page reads it.
export default function SearchBox() {
const router = useRouter();
const pathname = usePathname();
const searchParams = useSearchParams();
function handleChange(event) {
const params = new URLSearchParams(searchParams);
if (event.target.value) params.set("q", event.target.value);
else params.delete("q");
const query = params.toString();
router.replace(query ? `${pathname}?${query}` : pathname);
}
return (
<label>
Search <input defaultValue={searchParams.get("q") ?? ""} onChange={handleChange} />
</label>
);
}
body {
font: 16px/1.5 system-ui, sans-serif;
margin: 0;
color: #1c2430;
}
header,
main,
footer {
max-width: 36rem;
margin: 0 auto;
padding: 0.75rem 1rem;
}
header {
border-bottom: 1px solid #d6dde6;
}
nav {
display: flex;
gap: 1rem;
}
a {
color: #06617f;
}
h1 {
margin: 0.5rem 0;
}
.muted {
color: #5b6876;
}
.card {
border: 1px solid #d6dde6;
border-radius: 8px;
padding: 0.75rem 1rem;
margin-bottom: 0.75rem;
}
nav a[aria-current="page"] {
font-weight: 700;
text-decoration: none;
color: #1c2430;
}
export default function AboutPage() {
return (
<main>
<h1>About</h1>
<p>The current page's link is marked in the navigation.</p>
</main>
);
}
import { notFound } from "next/navigation";
import { getTopic } from "@/lib/topics.js";
export default async function TopicPage({ params }) {
const { slug } = await params;
const topic = await getTopic(slug);
if (!topic) notFound();
return (
<main>
<h1>{topic.title}</h1>
<p>{topic.summary}</p>
<p className="muted">
Day {topic.day} · {topic.minutes} minutes
</p>
</main>
);
}
// Pretend database of topics, looked up by their slug: the part of the URL
// that names them.
const topics = [
{ slug: "routing", title: "Routing", day: 1, minutes: 20, summary: "Folders become pages." },
{ slug: "layouts", title: "Layouts", day: 1, minutes: 20, summary: "Shared parts that wrap pages." },
{ slug: "server-components", title: "Server components", day: 2, minutes: 20, summary: "Components that run on the server." },
{ slug: "client-components", title: "Client components", day: 2, minutes: 20, summary: "Components that respond in the browser." },
{ slug: "dynamic-routes", title: "Dynamic routes", day: 3, minutes: 25, summary: "One file for many pages." },
];
const wait = () => new Promise((resolve) => setTimeout(resolve, 100));
export async function getTopics() {
await wait();
return topics;
}
export async function getTopic(slug) {
await wait();
return topics.find((topic) => topic.slug === slug) ?? null;
}
Runs with real Next.js on your computer: unzip, then npm install and npm run dev.
Hint 1: the idea
Picking at random and calling the router happen in the browser, so the button
is a client component. It can't load the topics itself: the server page has
them, and passes it what it needs.
Hint 2: a first step
Create app/RandomTopic.jsx with "use client". Have the page give it the
slugs as a prop, and have its button log a random one when clicked. When the
console shows a different slug on each press, navigate instead of logging.
In app/page.jsx, import it and render it under <SearchBox />, passing
slugs={topics.map((topic) => topic.slug)}.
The page sends only the slugs, a plain array, not whole topics: give a client
component the least it needs. router.push adds a history entry, so Back
returns to the list; router.replace wouldn't. The random pick happens in the
click handler, not during render, so it can't make the two renders differ.
Completion is saved in this browser only. It does not measure mastery.