Next.js Lesson 3: Pages & Navigation

▲ Next.js CourseLesson 3 of 12 · 25% complete

Next.js file-based routing means every file in app/ becomes a URL. The Link component handles navigation without full page reloads.

File-Based Routing

// File path → URL
app/page.tsx              → /
app/about/page.tsx        → /about
app/blog/page.tsx         → /blog
app/blog/[slug]/page.tsx  → /blog/any-post-slug
app/shop/[...path]/page.tsx → /shop/a/b/c (catch-all)
app/(auth)/login/page.tsx → /login  (group, no URL impact)

Link Component

import Link from "next/link";

export default function Navigation() {
  return (
    <nav>
      {/* Prefetches the page when link is visible! */}
      <Link href="/">Home</Link>
      <Link href="/about">About</Link>
      <Link href="/blog">Blog</Link>
      <Link href="/blog/my-first-post">First Post</Link>
      
      {/* Programmatic navigation */}
    </nav>
  );
}

useRouter & usePathname

"use client"; // required for hooks
import { useRouter, usePathname } from "next/navigation";

export default function BackButton() {
  const router = useRouter();
  const pathname = usePathname();  // current URL
  
  return (
    <div>
      <p>Current: {pathname}</p>
      <button onClick={() => router.push("/")}>Home</button>
      <button onClick={() => router.back()}>Back</button>
      <button onClick={() => router.refresh()}>Refresh</button>
    </div>
  );
}

🏋️ Practice Task

Build a navigation bar component (Navbar). It should highlight the active link (use usePathname to compare). Include links to /, /about, /blog, /contact. Add the Navbar to your root layout so it appears on every page.

💡 Hint: Highlight: className={pathname === href ? “active” : “”}. Add to app/layout.tsx: above {children}.

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *