Next.js foundations · Lesson 4 of 16
Client-side navigation
usePathname, useRouter and useSearchParams, and an active navbar link.
8 minutes2 games
Inside client components, next/navigation gives you hooks:
usePathname(): the current path (/courses/react).useSearchParams(): the query (?tab=lessons).useRouter(): navigate in code:router.push("/dashboard"),router.back(),router.refresh().
On the server, use redirect("/login") instead.
TypeScript
"use client"
import Link from "next/link"
import { usePathname } from "next/navigation"
const LINKS = [
{ href: "/dashboard", label: "Dashboard" },
{ href: "/courses", label: "Courses" },
{ href: "/settings", label: "Settings" },
]
export function NavBar() {
const pathname = usePathname()
return (
<nav>
{LINKS.map((l) => {
const active = pathname === l.href || pathname.startsWith(l.href + "/")
return (
<Link key={l.href} href={l.href} aria-current={active ? "page" : undefined}
className={active ? "font-bold underline" : ""}>
{l.label}
</Link>
)
})}
</nav>
)
}The logic is plain React, so try it here with pathname passed as a prop instead of usePathname:
React
const LINKS = [
{ href: "/dashboard", label: "Dashboard" },
{ href: "/courses", label: "Courses" },
{ href: "/settings", label: "Settings" },
]
function NavBar({ pathname }) {
return (
<nav style={{ display: "flex", gap: 12 }}>
{LINKS.map((l) => {
const active = pathname === l.href || pathname.startsWith(l.href + "/")
return <a key={l.href} href="#" style={{ fontWeight: active ? 700 : 400, textDecoration: active ? "underline" : "none" }}>{l.label}</a>
})}
</nav>
)
}
function App() {
const [path, setPath] = useState("/courses/react")
return (
<div>
<input value={path} onChange={(e) => setPath(e.target.value)} />
<NavBar pathname={path} />
</div>
)
}Complete the code
Complete it to send the user to the dashboard after login.
"use client" import { } from "next/navigation" export function LoginButton() { const router = useRouter() return <button onClick={async () => { await signIn(); router.("/dashboard") }}>Log in</button> }
Exercise
Finish NavBar: the active link (when pathname equals it or starts with it + /) renders as [Courses], the others without brackets. The page uses /courses/react.
The page should show: Dashboard [Courses] Settings
React
const LINKS = [
{ href: "/dashboard", label: "Dashboard" },
{ href: "/courses", label: "Courses" },
{ href: "/settings", label: "Settings" },
]
function NavBar({ pathname }) {
return <nav>{LINKS.map((l) => <span key={l.href}>{l.label} </span>)}</nav>
}
function App() {
return <NavBar pathname="/courses/react" />
}Learn more from
Played 0 of 2 games
Sign in to save your progress and earn XP.