Routing and Navigation in Next.js
File-Based Routing
Next.js uses file-based routing. Files in the app directory automatically become routes:
- app/page.tsx β /
- app/about/page.tsx β /about
- app/products/[id]/page.tsx β /products/:id
Dynamic Routes
Use square brackets for dynamic segments:
In app/products/[id]/page.tsx: export default function ProductPage({ params }) { return <h1>Product: {params.id}</h1> }
Navigation
Use the Link component for client-side navigation:
import Link from 'next/link';
export default function Navigation() { return ( <Link href="/about">About</Link> ) }
useRouter Hook
Programmatic navigation:
import { useRouter } from 'next/navigation';
export default function Button() { const router = useRouter(); return ( <button onClick={() => router.push('/about')}> Go to About </button> ) }
Master routing to build multi-page applications effectively.