Learn Next.js Β· 2/15

Routing Essentials: Navigating Your App

6 min read

Routing Essentials: Navigating Your App πŸ—ΊοΈ

Welcome, fellow coder! Today, we're diving into the heart of any web application: routing. In Next.js, routing is how you guide users through your app's different sections. Think of it as creating a map for your users to explore. Without a clear and efficient routing system, your users would be lost in a sea of components.

The introduction of the App Router in Next.js 13 has made this process more intuitive and powerful than ever. It allows for features like layouts, dynamic routes, and a new way of organizing your application's structure. So, buckle up as we explore the essentials of Next.js routing!

Folders as Routes: The App Router Convention πŸ“‚

The Problem: In traditional web development, managing routes often involves complex configuration files. As an application grows, these files can become a tangled mess, making it difficult to understand the URL structure.

The Solution: Next.js introduces a file-system-based router. This means the way you structure your folders and files directly determines your application's routes. It's like creating a physical filing system where the folder names become the paths in your URL.

How it Works:

The app directory is the heart of your application's routing. Each folder within the app directory represents a route segment. To create a new route, you simply create a new folder. For example, to create an /about route, you would create a folder named about inside the app directory.

To make a route publicly accessible, you need to add a page.js or page.tsx file inside the corresponding folder. This file will export a React component that will be rendered for that route.

Example:

Let's create a simple two-page website: a homepage and an about page.

Your file structure would look like this:

stata
app/
β”œβ”€β”€ page.tsx       // This is our homepage (/)
└── about/
    └── page.tsx   // This is our about page (/about)

app/page.tsx:

jsx
export default function HomePage() {
  return <h1>Welcome to the Homepage!</h1>;
}

app/about/page.tsx:

jsx
export default function AboutPage() {
  return <h1>This is the About Page.</h1>;
}

And just like that, you've created two routes! No complex configuration needed. It's clean, intuitive, and scales beautifully as your application grows.

A Little Industry Secret: While you can put all your files directly in the app directory, a common practice for larger applications is to use a src folder to keep your application source code organized.

Pages and Layouts: Building the UI Skeleton 🦴

The Problem: Many websites have common UI elements like a header, footer, and sidebar that are present on every page. Without a proper structure, you'd have to repeat this code in every single page component, leading to code duplication and maintenance nightmares.

The Solution: Next.js provides a powerful solution with layout.js (or layout.tsx) files. A layout is a shared UI that wraps multiple pages. Think of it as a template that provides the basic structure for a set of pages.

How it Works:

You can define a layout by creating a layout.js file and exporting a React component. This component must accept a children prop, which will be the content of the page it's wrapping.

The most important layout is the root layout, located in app/layout.tsx. This layout is required and wraps every single page in your application. It must include the <html> and <body> tags.

Example:

Let's create a root layout with a simple header and footer.

app/layout.tsx:

jsx
export default function RootLayout({
  children,
}: {
  children: React.ReactNode;
}) {
  return (
    <html lang="en">
      <body>
        <header>
          <nav>
            {/* Navigation links will go here */}
          </nav>
        </header>
        <main>{children}</main>
        <footer>
          <p>Β© 2024 Our Awesome Website</p>
        </footer>
      </body>
    </html>
  );
}

Now, any page.tsx file within the app directory will be automatically wrapped by this RootLayout. The content of the page will be rendered where the {children} prop is placed. This is a fantastic way to maintain a consistent look and feel across your application while reducing code duplication.

Fun Fact: Layouts in Next.js preserve state and don't re-render on navigation between pages that share the same layout. This leads to a much smoother and faster user experience.

The <Link> Component: Seamless Client-Side Navigation πŸš€

The Problem: Traditional web navigation, using the <a> tag, causes a full page reload every time a user clicks a link. This can be slow and jarring, especially in modern single-page applications (SPAs) where a seamless experience is expected.

The Solution: Next.js provides the <Link> component for client-side navigation. This component enables navigation between pages within your Next.js application without a full page reload, resulting in a much faster and smoother user experience.

How it Works:

The <Link> component is used in place of the traditional <a> tag for internal navigation. It takes an href prop, which is the path to the page you want to navigate to.

Example:

Let's add some navigation to our header in the RootLayout.

app/layout.tsx:

jsx
import Link from 'next/link';

export default function RootLayout({
  children,
}: {
  children: React.ReactNode;
}) {
  return (
    <html lang="en">
      <body>
        <header>
          <nav>
            <Link href="/">Home</Link>
            <Link href="/about">About</Link>
          </nav>
        </header>
        <main>{children}</main>
        <footer>
          <p>Β© 2024 Our Awesome Website</p>
        </footer>
      </body>
    </html>
  );
}

Now, when a user clicks on the "Home" or "About" links, the page content will update without a full page refresh. This is because Next.js handles the routing on the client-side.

Under the Hood: The <Link> component still renders an <a> tag in the HTML. This is great for SEO as web crawlers can still discover and index your pages. When JavaScript is enabled, the <Link> component intercepts the click event and handles the navigation on the client-side. If JavaScript is disabled, the <a> tag works as a normal link, ensuring your site is still navigable.

Active Links and the usePathname Hook 🚦

The Problem: When a user is on a particular page, it's a common user experience (UX) practice to visually indicate which link in the navigation is currently active. Without a way to know the current URL path, this can be tricky to implement.

The Solution: Next.js provides the usePathname hook, which allows you to read the current URL's pathname. This makes it easy to conditionally apply styles to your active links.

How it Works:

The usePathname hook can only be used in a Client Component. Therefore, you'll need to add the "use client"; directive at the top of your file. The hook returns a string of the current URL's pathname.

Example:

Let's create a Navigation component that highlights the active link.

app/components/Navigation.tsx:

jsx
"use client";

import Link from 'next/link';
import { usePathname } from 'next/navigation';

export default function Navigation() {
  const pathname = usePathname();

  return (
    <nav>
      <Link href="/" className={pathname === '/' ? 'active' : ''}>
        Home
      </Link>
      <Link href="/about" className={pathname === '/about' ? 'active' : ''}>
        About
      </Link>
    </nav>
  );
}

Now, in your RootLayout, you can import and use this Navigation component. You'll also need to add some CSS to style the .active class.

This simple yet powerful hook allows you to create a much more intuitive and user-friendly navigation experience.


Further Reading πŸ“š

Challenge

You are tasked with building the foundational routing and navigation for a new Next.js application using the App Router.

Your goal is to write the code for four distinct files within a single editor block, separated by comments as provided in the initial code.

  1. Root Layout (app/layout.tsx): Create the root layout for the entire application. It must include the essential <html> and <body> tags and render a shared Navigation component above the page content (children).
  2. Navigation Component (app/components/Navigation.tsx):
    • This component must be a Client Component.
    • It should contain two navigation links using the Next.js <Link> component: one for the homepage (/) and one for the about page (/about).
    • Implement active link styling. Use the usePathname hook to determine the current route and conditionally apply a className="active" to the <Link> that matches the current path.
  3. Home Page (app/page.tsx): Create a simple component to be rendered at the root URL (/).
  4. About Page (app/about/page.tsx): Create another simple component to be rendered at the /about URL.

Expected result

Your final code should consist of four complete React components, structured as if they were in separate files.

  • app/layout.tsx: A RootLayout component that correctly structures the HTML document. It should import the Navigation component and render it within the <body>, followed by its children prop. It must export this component as the default.
  • app/components/Navigation.tsx:
    • The file's code must begin with the "use client"; directive.
    • It should import Link from next/link and usePathname from next/navigation.
    • The exported default component should render a <nav> element.
    • Inside the <nav>, there should be two <Link> components with href props set to / and /about.
    • The className for each link must be conditionally set to 'active' if its href matches the value from usePathname(), and an empty string or another class otherwise.
  • app/page.tsx: A default exported server component named HomePage (or similar) that returns a simple JSX element, like <h1>Welcome to the Home Page</h1>.
  • app/about/page.tsx: A default exported server component named AboutPage (or similar) that returns a simple JSX element, like <h1>About Us</h1>.
jsx

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.