Course
Linking and Navigating
Next.js Mastery: From Fundamentals to Full-Stack
Unlock the power of Next.js with this comprehensive course! Starting with the basics, you’ll learn essential skills such as routing, data fetching, and styling. Progress through practical projects, including building your own React Notes app, to gain hands-on experience. Dive into the source code to understand the inner workings and core principles of Next.js. Perfect for developers with a basic knowledge of React and Node.js, this course ensures you’ll be ready to create high-performance full-stack applications efficiently. Join us and master Next.js, backed by industry experts and a supportive learning community.
Link
In the previous section, we learned how to define routes. Now, let's dive into implementing links and navigation in Next.js.
"Navigation" involves transitioning between pages using JavaScript. This method is typically faster than the browser's default page reload since it updates only necessary components instead of the whole page.
In Next.js, you can navigate routes in four ways:
<Link>
The
<Link>
component in Next.js extends the native <a>
tag, allowing prefetching and client-side navigation. This is the primary and recommended method for handling routing.
Basic Usage:
import Link from 'next/link'
export default function Page() { return <Link href="/dashboard">Dashboard</Link>}
Dynamic Rendering:
import Link from 'next/link'
export default function PostList({ posts }) { return ( <ul> {posts.map((post) => ( <li key={post.id}> <Link href={`/blog/${post.slug}`}>{post.title}</Link> </li> ))} </ul> )}
useRouter
The
useRouter
hook lets you change routes. Note that this hook should be used in client components.'use client'
import { useRouter } from 'next/navigation'
export default function Page() { const router = useRouter()
return ( <button type="button" onClick={() => router.push('/dashboard')}> Dashboard </button> )}
redirect
For server components, use the
redirect
function:import { redirect } from 'next/navigation'
async function fetchTeam(id) { const res = await fetch('https://...') if (!res.ok) return undefined return res.json()}
export default async function Profile({ params }) { const team = await fetchTeam(params.id) if (!team) { redirect('/login') } // ...}
History API
You can also use the native
window.history.pushState
and window.history.replaceState
methods to update the browser's history stack.
Example with
pushState
to sort a list:'use client'
import { useSearchParams } from 'next/navigation'
export default function SortProducts() { const searchParams = useSearchParams()
function updateSorting(sortOrder) { const params = new URLSearchParams(searchParams.toString()) params.set('sort', sortOrder) window.history.pushState(null, '', `?${params.toString()}`) }
return ( <> <button onClick={() => updateSorting('asc')}>Sort Ascending</button> <button onClick={() => updateSorting('desc')}>Sort Descending</button> </> )}
Example with
replaceState
to switch locale:'use client'
import { usePathname } from 'next/navigation'
export default function LocaleSwitcher() { const pathname = usePathname()
function switchLocale(locale) { const newPath = `/${locale}${pathname}` window.history.replaceState(null, '', newPath) }
return ( <> <button onClick={() => switchLocale('en')}>English</button> <button onClick={() => switchLocale('fr')}>French</button> </> )}
Summary
You've learned four methods to implement navigation in Next.js! 🎉 🎉
While we didn't delve into specific concepts like server and client components or various hooks, this overview provides a foundation for using navigation-related features in your demos. More details on these concepts will follow in subsequent articles.