Day 4 β Navigation & Linking: Moving Between Pages
π§ Day 4 β Navigation & Linking: Moving Between Pages
Zero to Hero β Hands-on Next.js Tutorial
In a Single Page Application (SPA), we never want to do a βhard refreshβ of the browser.
We want to swap the content instantly. Next.js makes this incredibly fast with the <Link> component.
π¦ 1. The <Link> Component
Never use the HTML <a> tag for internal links. It causes a full page reload (slow!).
Instead, import Link from next/link.
import Link from 'next/link';
export default function NavBar() {
return (
<nav className="flex gap-4">
<Link href="/">Home</Link>
<Link href="/about">About</Link>
<Link href="/blog/123">Read Post</Link>
</nav>
);
}
Why use <Link>?
- Client-side Navigation: Instant transitions.
- Prefetching: Next.js automatically loads the code for the linked page in the background as soon as the link enters the viewport. By the time you click, itβs already there. β‘
π© 2. Active Links (usePathname)
How do we style the βHomeβ link differently if we are currently on the Home page?
We use the usePathname() hook.
Note: Since hooks need the browser, this must be a Client Component ('use client').
'use client'; // Required for hooks!
import Link from 'next/link';
import { usePathname } from 'next/navigation';
export default function NavLinks() {
const pathname = usePathname();
return (
<nav>
<Link
href="/dashboard"
className={pathname === '/dashboard' ? 'text-blue-500 font-bold' : 'text-gray-500'}
>
Dashboard
</Link>
</nav>
);
}
π§ 3. Programmatic Navigation (useRouter)
Sometimes you need to navigate after an action (e.g., submitting a login form), not just by clicking a link.
Use useRouter from next/navigation.
'use client';
import { useRouter } from 'next/navigation';
export default function LoginPage() {
const router = useRouter();
const handleLogin = async () => {
// ... perform login logic ...
router.push('/dashboard'); // Navigate to dashboard
// router.replace('/dashboard'); // Replace history (can't go back)
};
return <button onClick={handleLogin}>Log In</button>;
}
π₯ 4. Server-Side Redirects
If you are on the server (e.g., in a Server Component or Server Action) and want to redirect the user, use the redirect function.
import { redirect } from 'next/navigation';
export default async function ProtectedPage() {
const session = await getSession();
if (!session) {
redirect('/login'); // Throws an error to stop execution and redirect
}
return <h1>Welcome back!</h1>;
}
π§ͺ Challenge: Day 4
- Create a
NavBarcomponent. - Add links to Home (
/), About (/about), and Blog (/blog). - Make the current link bold and red using
usePathname. - Include this
NavBarin yoursrc/app/layout.tsxso it appears on every page.
See you tomorrow for Styling & Fonts! π¨