Next.js course ยท Module 2: Routing and Layouts

Navigation with the Link Component and useRouter

24 min read ยท
In this lesson6

In the Quantum Metropolis, the transportation system allows residents to move smoothly between different districts and facilities. These advanced vehicles, called Q-Links, can instantly transport passengers to virtually any location in the city, without the need to reload the entire transport infrastructure.

In the world of Next.js 16, the Link component and useRouter hook play a similar role. These tools enable creating smooth, efficient navigation between different parts of the application, without the need to reload the entire page.

The Link component is the fundamental navigation element in Next.js 16, working like a Q-Link in the Quantum Metropolis - it takes the user to a specified destination without unnecessary delays or disruptions.

import Link from 'next/link';

export default function Navigation() {
  return (
    <nav className="flex space-x-6 py-4">
      <Link
        href="/"
        className="text-indigo-600 hover:text-indigo-800 transition-colors"
      >
        Home
      </Link>
      <Link
        href="/destinations"
        className="text-indigo-600 hover:text-indigo-800 transition-colors"
      >
        Destinations
      </Link>
      <Link
        href="/flights"
        className="text-indigo-600 hover:text-indigo-800 transition-colors"
      >
        Flights
      </Link>
      <Link
        href="/about"
        className="text-indigo-600 hover:text-indigo-800 transition-colors"
      >
        About Us
      </Link>
    </nav>
  );
}

This simple code creates a basic navigation bar that allows users to move between different sections of the application. Notice that the Link component accepts properties like href (navigation target) and we can pass it classic HTML attributes like className for styling.

Just like Q-Links in the Quantum Metropolis, which offer much more than traditional vehicles, the Link component in Next.js 16 surpasses the regular HTML <a> tag in many ways:

  1. Prefetching - automatically loads the target page in the background when the link is visible in the browser viewport, which drastically speeds up navigation.
  2. Client-side navigation - transitions between pages without a full page reload, updating only what is necessary.
  3. Automatic optimization - Link components are automatically optimized for the App Router application, taking into account features like prefetching of dynamic routes.
  4. Focus management - after navigation, focus is properly transferred, improving the application's accessibility.

The Link component offers several advanced options that enhance its functionality:

1. Dynamic Routes

// Destination card component
function DestinationCard({ destination }: { destination: { id: string; name: string; shortDescription: string } }) {
  return (
    <Link
      href={`/destinations/${destination.id}`}
      className="block p-4 border rounded-lg hover:shadow-md transition-shadow"
    >
      <h2 className="text-xl font-semibold">{destination.name}</h2>
      <p className="text-gray-600">{destination.shortDescription}</p>
    </Link>
  );
}

2. Passing Query Parameters

// Search filter component
function SearchFilter({ currentCategory, currentSort }: { currentCategory: string; currentSort: string }) {
  return (
    <div className="flex space-x-4">
      <Link
        href={{
          pathname: '/search',
          query: { category: 'planets', sort: currentSort },
        }}
        className={`px-3 py-1 rounded ${currentCategory === 'planets' ? 'bg-indigo-600 text-white' : 'bg-gray-200'}`}
      >
        Planets
      </Link>
      <Link
        href={{
          pathname: '/search',
          query: { category: 'moons', sort: currentSort },
        }}
        className={`px-3 py-1 rounded ${currentCategory === 'moons' ? 'bg-indigo-600 text-white' : 'bg-gray-200'}`}
      >
        Moons
      </Link>
      <Link
        href={{
          pathname: '/search',
          query: { category: 'stars', sort: currentSort },
        }}
        className={`px-3 py-1 rounded ${currentCategory === 'stars' ? 'bg-indigo-600 text-white' : 'bg-gray-200'}`}
      >
        Stars
      </Link>
    </div>
  );
}

3. Overriding Default Behavior

// "Scroll to top" button component
function ScrollToTopButton() {
  const handleClick = (e) => {
    e.preventDefault();
    window.scrollTo({ top: 0, behavior: 'smooth' });
  };

  return (
    <Link
      href="#top"
      onClick={handleClick}
      className="fixed bottom-4 right-4 p-2 bg-indigo-600 text-white rounded-full"
      aria-label="Scroll to top"
    >
      <svg xmlns="http://www.w3.org/2000/svg" className="h-6 w-6" fill="none" viewBox="0 0 24 24" stroke="currentColor">
        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M5 10l7-7m0 0l7 7m-7-7v18" />
      </svg>
    </Link>
  );
}

4. Scroll and Focus Handling

<Link
  href="/destinations"
  scroll={false} // Disables automatic scrolling to top of page
>
  Destinations (no scrolling)
</Link>

5. Prefetch

<Link
  href="/rarely-visited-page"
  prefetch={false} // Disables automatic prefetching
>
  Rarely visited page
</Link>

By default, Link automatically prefetches pages that are visible in the viewport. You can control this with the prefetch property.

Since Next.js 13, the Link component renders the <a> tag itself and passes the appropriate attributes to it, so in Next.js 16 you don't need to nest an additional <a> tag inside the Link component. This improvement allows for more concise code:

// Correct usage in Next.js 16
<Link
  href="/destinations"
  className="text-blue-600 hover:underline"
  target="_blank"
  rel="noopener noreferrer"
>
  View Destinations
</Link>

useRouter - Programmatic Navigation

While the Link component is ideal for declarative navigation (visible in the UI), sometimes we need to navigate programmatically - similarly to the Quantum Metropolis, where the central artificial intelligence can direct Q-Links to new locations based on various conditions or events.

In Next.js 16, the useRouter hook from the next/navigation package enables exactly this kind of dynamic navigation.

Basic Usage of useRouter

'use client';

import { useRouter } from 'next/navigation';

export default function BookingForm() {
  const router = useRouter();

  const handleSubmit = async (event) => {
    event.preventDefault();

    // Form processing logic...
    const bookingSuccess = await submitBooking(formData);

    if (bookingSuccess) {
      // After successful submission, redirect the user
      router.push('/booking/confirmation');
    }
  };

  return (
    <form onSubmit={handleSubmit} className="space-y-6">
      {/* Form fields... */}
      <button
        type="submit"
        className="w-full py-2 px-4 bg-indigo-600 text-white rounded"
      >
        Book a Trip
      </button>
    </form>
  );
}

Note: Remember that useRouter is a React hook, so it can only be used in Client components (marked with 'use client';).

useRouter Hook Methods

The useRouter hook provides several useful methods:

1. router.push(url)

Navigates to the given URL, adding a new entry to the browser history:

const router = useRouter();

function navigateToHome() {
  router.push('/');
}

function navigateToDestination(destinationId) {
  router.push(`/destinations/${destinationId}`);
}

function navigateWithQueryParams() {
  router.push('/search?category=planets&sort=distance');
}

2. router.replace(url)

Similar to push, but replaces the current history entry instead of adding a new one:

function redirectToLogin() {
  router.replace('/login'); // The user won't be able to go back to the previous page with the "Back" button
}

3. router.refresh()

Refreshes the current page, re-fetching data while preserving the DOM state:

function refreshData() {
  router.refresh(); // Re-fetches data from the server without a full page reload
}

4. router.back()

Navigates to the previous page in browser history:

function goBack() {
  router.back();
}

5. router.forward()

Navigates to the next page in browser history:

function goForward() {
  router.forward();
}

6. router.prefetch(href)

Prefetches the given URL:

function prefetchImportantPage() {
  router.prefetch('/important-page');
}

Practical useRouter Usage Examples

Example 1: Navigation Assistant

'use client';

import { useState, useEffect } from 'react';
import { useRouter } from 'next/navigation';

export default function NavigationAssistant() {
  const router = useRouter();
  const [destination, setDestination] = useState('');
  const [suggestions, setSuggestions] = useState([]);

  useEffect(() => {
    if (destination.length < 2) {
      setSuggestions([]);
      return;
    }

    // Simulating fetching suggestions from API
    const fetchSuggestions = async () => {
      // In a real application, we would fetch data from the API
      const mockSuggestions = [
        { id: 'mars', name: 'Mars', type: 'planet' },
        { id: 'mars-colony-alpha', name: 'Mars Colony Alpha', type: 'colony' },
        { id: 'martian-canyon', name: 'Great Martian Canyon', type: 'landmark' }
      ].filter(item =>
        item.name.toLowerCase().includes(destination.toLowerCase())
      );

      setSuggestions(mockSuggestions);
    };

    fetchSuggestions();
  }, [destination]);

  const handleSelect = (suggestion) => {
    // Route selection based on suggestion type
    switch(suggestion.type) {
      case 'planet':
        router.push(`/destinations/${suggestion.id}`);
        break;
      case 'colony':
        router.push(`/colonies/${suggestion.id}`);
        break;
      case 'landmark':
        router.push(`/landmarks/${suggestion.id}`);
        break;
      default:
        router.push(`/search?q=${encodeURIComponent(suggestion.name)}`);
    }
  };

  return (
    <div className="relative w-full max-w-md">
      <input
        type="text"
        value={destination}
        onChange={(e) => setDestination(e.target.value)}
        className="w-full p-3 border border-gray-300 rounded-lg shadow-sm focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500"
      />

      {suggestions.length > 0 && (
        <div className="absolute z-10 w-full mt-1 bg-white rounded-lg shadow-lg border border-gray-200">
          <ul>
            {suggestions.map((suggestion) => (
              <li
                key={suggestion.id}
                className="px-4 py-3 hover:bg-gray-100 cursor-pointer flex items-center"
                onClick={() => handleSelect(suggestion)}
              >
                <div className="w-8 h-8 mr-3 flex items-center justify-center rounded-full bg-indigo-100 text-indigo-800">
                  {suggestion.type === 'planet' ? 'P' : suggestion.type === 'colony' ? 'C' : 'L'}
                </div>
                <div>
                  <div className="font-medium">{suggestion.name}</div>
                  <div className="text-sm text-gray-500 capitalize">{suggestion.type}</div>
                </div>
              </li>
            ))}
          </ul>
        </div>
      )}
    </div>
  );
}

Example 2: Multi-Step Booking Form

'use client';

import { useState } from 'react';
import { useRouter } from 'next/navigation';

export default function MultiStepBookingForm() {
  const router = useRouter();
  const [step, setStep] = useState(1);
  const [formData, setFormData] = useState({
    destination: '',
    departureDate: '',
    returnDate: '',
    passengers: 1,
    contactEmail: '',
    contactPhone: ''
  });

  const updateFormData = (field, value) => {
    setFormData(prev => ({ ...prev, [field]: value }));
  };

  const goToNextStep = () => {
    setStep(prev => prev + 1);
  };

  const goToPreviousStep = () => {
    setStep(prev => prev - 1);
  };

  const submitForm = async () => {
    try {
      // Here we would normally send data to the API
      console.log('Sending data:', formData);

      // Simulating waiting for API response
      await new Promise(resolve => setTimeout(resolve, 1000));

      // Redirect to confirmation page with booking ID
      router.push('/booking/confirmation?id=QV123456789');
    } catch (error) {
      console.error('Booking error:', error);
      // Error handling
    }
  };

  return (
    <div className="max-w-3xl mx-auto p-6 bg-white rounded-lg shadow-md">
      <div className="mb-8">
        <div className="flex items-center">
          {[1, 2, 3].map((i) => (
            <div key={i} className="flex items-center">
              <div className={`w-10 h-10 rounded-full flex items-center justify-center ${
                i === step ? 'bg-indigo-600 text-white' :
                i < step ? 'bg-green-500 text-white' : 'bg-gray-200 text-gray-700'
              }`}>
                {i < step ? 'OK' : i}
              </div>
              {i < 3 && (
                <div className={`h-1 w-16 ${i < step ? 'bg-green-500' : 'bg-gray-200'}`}></div>
              )}
            </div>
          ))}
        </div>
        <div className="flex justify-between mt-2">
          <span>Destination</span>
          <span>Trip Details</span>
          <span>Contact Information</span>
        </div>
      </div>

      {step === 1 && (
        <div className="space-y-4">
          <h2 className="text-2xl font-semibold">Choose a Destination</h2>

          <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
            {['Mars', 'Europa', 'Titan'].map((dest) => (
              <div
                key={dest}
                onClick={() => updateFormData('destination', dest)}
                className={`p-4 border rounded-lg cursor-pointer ${
                  formData.destination === dest ? 'border-indigo-600 bg-indigo-50' : 'border-gray-200'
                }`}
              >
                <h3 className="font-semibold">{dest}</h3>
                <p className="text-sm text-gray-600">Discover the wonders of {dest}</p>
              </div>
            ))}
          </div>

          <div className="flex justify-end mt-6">
            <button
              onClick={goToNextStep}
              disabled={!formData.destination}
              className={`px-6 py-2 rounded-lg ${
                formData.destination ? 'bg-indigo-600 text-white' : 'bg-gray-200 text-gray-500 cursor-not-allowed'
              }`}
            >
              Next
            </button>
          </div>
        </div>
      )}

      {step === 2 && (
        <div className="space-y-4">
          <h2 className="text-2xl font-semibold">Trip Details</h2>

          <div className="space-y-4">
            <div>
              <label className="block mb-1">Departure Date</label>
              <input
                type="date"
                value={formData.departureDate}
                onChange={(e) => updateFormData('departureDate', e.target.value)}
                className="w-full p-2 border border-gray-300 rounded"
                min={new Date().toISOString().split('T')[0]}
              />
            </div>

            <div>
              <label className="block mb-1">Return Date</label>
              <input
                type="date"
                value={formData.returnDate}
                onChange={(e) => updateFormData('returnDate', e.target.value)}
                className="w-full p-2 border border-gray-300 rounded"
                min={formData.departureDate || new Date().toISOString().split('T')[0]}
              />
            </div>

            <div>
              <label className="block mb-1">Number of Passengers</label>
              <input
                type="number"
                value={formData.passengers}
                onChange={(e) => updateFormData('passengers', e.target.value)}
                className="w-full p-2 border border-gray-300 rounded"
                min="1"
                max="10"
              />
            </div>
          </div>

          <div className="flex justify-between mt-6">
            <button
              onClick={goToPreviousStep}
              className="px-6 py-2 border border-gray-300 rounded-lg"
            >
              Back
            </button>
            <button
              onClick={goToNextStep}
              disabled={!formData.departureDate || !formData.returnDate}
              className={`px-6 py-2 rounded-lg ${
                formData.departureDate && formData.returnDate ?
                'bg-indigo-600 text-white' :
                'bg-gray-200 text-gray-500 cursor-not-allowed'
              }`}
            >
              Next
            </button>
          </div>
        </div>
      )}

      {step === 3 && (
        <div className="space-y-4">
          <h2 className="text-2xl font-semibold">Contact Information</h2>

          <div className="space-y-4">
            <div>
              <label className="block mb-1">Email</label>
              <input
                type="email"
                value={formData.contactEmail}
                onChange={(e) => updateFormData('contactEmail', e.target.value)}
                className="w-full p-2 border border-gray-300 rounded"
              />
            </div>

            <div>
              <label className="block mb-1">Phone</label>
              <input
                type="tel"
                value={formData.contactPhone}
                onChange={(e) => updateFormData('contactPhone', e.target.value)}
                className="w-full p-2 border border-gray-300 rounded"
              />
            </div>
          </div>

          <div className="mt-6 p-4 bg-gray-50 rounded-lg">
            <h3 className="font-semibold mb-2">Summary</h3>
            <div className="grid grid-cols-2 gap-2 text-sm">
              <div>Destination:</div>
              <div className="font-medium">{formData.destination}</div>

              <div>Departure Date:</div>
              <div className="font-medium">{formData.departureDate}</div>

              <div>Return Date:</div>
              <div className="font-medium">{formData.returnDate}</div>

              <div>Passengers:</div>
              <div className="font-medium">{formData.passengers}</div>
            </div>
          </div>

          <div className="flex justify-between mt-6">
            <button
              onClick={goToPreviousStep}
              className="px-6 py-2 border border-gray-300 rounded-lg"
            >
              Back
            </button>
            <button
              onClick={submitForm}
              disabled={!formData.contactEmail || !formData.contactPhone}
              className={`px-6 py-2 rounded-lg ${
                formData.contactEmail && formData.contactPhone ?
                'bg-indigo-600 text-white' :
                'bg-gray-200 text-gray-500 cursor-not-allowed'
              }`}
            >
              Book a Trip
            </button>
          </div>
        </div>
      )}
    </div>
  );
}

usePathname and useSearchParams - Route Monitoring

In the Quantum Metropolis, the traffic monitoring system constantly tracks Q-Link positions, enabling the central AI to adjust transport parameters in real time. In Next.js 16, the usePathname and useSearchParams hooks serve a similar function.

usePathname - Tracking the Current Path

'use client';

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

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

  const navItems = [
    { label: 'Home', href: '/' },
    { label: 'Destinations', href: '/destinations' },
    { label: 'Flights', href: '/flights' },
    { label: 'Offers', href: '/offers' },
    { label: 'About Us', href: '/about' }
  ];

  return (
    <nav className="bg-white shadow">
      <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
        <div className="flex justify-between h-16">
          <div className="flex">
            <div className="shrink-0 flex items-center">
              <img className="h-8 w-auto" src="/logo.svg" alt="Quantum Voyages" />
            </div>
            <div className="hidden sm:ml-6 sm:flex sm:space-x-8">
              {navItems.map((item) => {
                const isActive = pathname === item.href ||
                  (item.href !== '/' && pathname.startsWith(item.href));

                return (
                  <Link
                    key={item.href}
                    href={item.href}
                    className={`inline-flex items-center px-1 pt-1 border-b-2 text-sm font-medium ${
                      isActive
                        ? 'border-indigo-500 text-gray-900'
                        : 'border-transparent text-gray-500 hover:border-gray-300 hover:text-gray-700'
                    }`}
                  >
                    {item.label}
                  </Link>
                );
              })}
            </div>
          </div>
          <div className="hidden sm:ml-6 sm:flex sm:items-center">
            <Link
              href="/dashboard"
              className="px-4 py-2 text-sm rounded-md text-white bg-indigo-600 hover:bg-indigo-700"
            >
              My Account
            </Link>
          </div>
        </div>
      </div>
    </nav>
  );
}

In this example, usePathname allows us to determine the current path, which enables highlighting the active item in the navigation menu.

useSearchParams - Accessing Query Parameters

'use client';

import { useSearchParams } from 'next/navigation';

export default function SearchResultsHeader() {
  const searchParams = useSearchParams();

  const query = searchParams.get('q') || '';
  const category = searchParams.get('category') || 'all';
  const sort = searchParams.get('sort') || 'relevance';

  return (
    <div className="mb-6">
      <h1 className="text-3xl font-bold mb-2">
        {query ? `Search results for "${query}"` : 'All destinations'}
      </h1>
      <div className="flex items-center text-sm text-gray-600">
        <span>Category: <strong className="capitalize">{category}</strong></span>
        <span className="mx-2">โ€ข</span>
        <span>Sorting: <strong className="capitalize">{
          sort === 'relevance' ? 'Relevance' :
          sort === 'price-asc' ? 'Price: lowest first' :
          sort === 'price-desc' ? 'Price: highest first' :
          sort === 'rating' ? 'Rating' : 'Relevance'
        }</strong></span>
      </div>
    </div>
  );
}

This code demonstrates how useSearchParams allows reading and utilizing query parameters from the URL, which can determine various aspects of the displayed page.

Combining useSearchParams with Navigation

'use client';

import { useSearchParams, useRouter, usePathname } from 'next/navigation';

export default function SearchFilters() {
  const router = useRouter();
  const pathname = usePathname();
  const searchParams = useSearchParams();

  // Get current search parameters
  const currentCategory = searchParams.get('category') || 'all';
  const currentSort = searchParams.get('sort') || 'relevance';
  const currentQuery = searchParams.get('q') || '';

  // Function to update parameters while preserving existing ones
  const createQueryString = (name, value) => {
    const params = new URLSearchParams(searchParams);
    params.set(name, value);

    return params.toString();
  };

  const handleCategoryChange = (category) => {
    router.push(`${pathname}?${createQueryString('category', category)}`);
  };

  const handleSortChange = (sort) => {
    router.push(`${pathname}?${createQueryString('sort', sort)}`);
  };

  return (
    <div className="mb-8 space-y-4">
      <div>
        <h2 className="text-lg font-medium mb-2">Categories</h2>
        <div className="flex flex-wrap gap-2">
          {['all', 'planets', 'moons', 'stations'].map((category) => (
            <button
              key={category}
              onClick={() => handleCategoryChange(category)}
              className={`px-4 py-2 rounded-full text-sm ${
                currentCategory === category
                  ? 'bg-indigo-600 text-white'
                  : 'bg-gray-200 text-gray-800 hover:bg-gray-300'
              }`}
            >
              {category === 'all' ? 'All' :
               category === 'planets' ? 'Planets' :
               category === 'moons' ? 'Moons' : 'Space stations'}
            </button>
          ))}
        </div>
      </div>

      <div>
        <h2 className="text-lg font-medium mb-2">Sorting</h2>
        <select
          value={currentSort}
          onChange={(e) => handleSortChange(e.target.value)}
          className="w-full sm:w-auto p-2 border border-gray-300 rounded-md"
        >
          <option value="relevance">Relevance</option>
          <option value="price-asc">Price: lowest first</option>
          <option value="price-desc">Price: highest first</option>
          <option value="rating">Rating</option>
          <option value="distance">Distance</option>
        </select>
      </div>
    </div>
  );
}

This example demonstrates how to effectively combine useSearchParams with useRouter and usePathname to create interactive filters that update the URL and page content without a full reload.

Intercepting Routes

In the Quantum Metropolis, sometimes a Q-Link can change its route mid-flight to handle a passenger's special request without interrupting the main journey. In Next.js 16, this concept is implemented through "Intercepting Routes".

Basic Concept of Route Interception

Route interception allows you to "intercept" normal navigation to a specific path and display an alternative UI, often an overlay (modal) on the current page, instead of a complete page change.

The implementation is based on a special folder naming convention:

  1. (.) - intercepts segments at the same level
  2. (..) - intercepts segments one level up
  3. (..)(..) - intercepts segments two levels up
  4. (...) - intercepts segments from the application root

Directory structure:

app/
  โ”œโ”€โ”€ destinations/
  โ”‚   โ”œโ”€โ”€ page.tsx              # Destinations list page /destinations
  โ”‚   โ””โ”€โ”€ [planet]/
  โ”‚       โ”œโ”€โ”€ layout.tsx        # Renders {children} and the {modal} slot
  โ”‚       โ”œโ”€โ”€ page.tsx          # Specific planet page /destinations/mars
  โ”‚       โ”œโ”€โ”€ gallery/
  โ”‚       โ”‚   โ””โ”€โ”€ page.tsx      # Full gallery /destinations/mars/gallery
  โ”‚       โ””โ”€โ”€ @modal/
  โ”‚           โ”œโ”€โ”€ default.tsx   # Returns null while the modal is closed (required in Next.js 16)
  โ”‚           โ””โ”€โ”€ (.)gallery/
  โ”‚               โ””โ”€โ”€ page.tsx  # Intercepts /destinations/mars/gallery as modal

The @modal slot folder is not a URL segment, so the gallery in the same [planet] segment is intercepted by (.)gallery, not (..)gallery (that would intercept /destinations/gallery).

Implementation:

// app/destinations/page.tsx - Destinations home
import Link from 'next/link';

export default function DestinationsPage() {
  const destinations = [
    { id: 'mars', name: 'Mars', imageUrl: '/images/mars.jpg' },
    { id: 'europa', name: 'Europa', imageUrl: '/images/europa.jpg' },
    { id: 'titan', name: 'Titan', imageUrl: '/images/titan.jpg' }
  ];

  return (
    <div className="container mx-auto py-12 px-4">
      <h1 className="text-4xl font-bold mb-8">Galactic Destinations</h1>

      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-8">
        {destinations.map(destination => (
          <Link
            key={destination.id}
            href={`/destinations/${destination.id}`}
            className="block group"
          >
            <div className="relative h-64 rounded-lg overflow-hidden shadow-lg">
              <img
                src={destination.imageUrl}
                alt={destination.name}
                className="w-full h-full object-cover transition-transform group-hover:scale-105"
              />
              <div className="absolute inset-0 bg-gradient-to-t from-black/70 to-transparent flex items-end">
                <h2 className="text-white text-2xl font-bold p-4">
                  {destination.name}
                </h2>
              </div>
            </div>
          </Link>
        ))}
      </div>
    </div>
  );
}
// app/destinations/[planet]/page.tsx - Specific planet page
import Link from 'next/link';

export default async function PlanetPage({ params }: { params: Promise<{ planet: string }> }) {
  const { planet } = await params;

  // Simulated gallery data
  const galleryImages = Array.from({ length: 6 }, (_, i) => ({
    id: i + 1,
    src: `/images/${planet}/${i + 1}.jpg`,
    alt: `Photo of ${planet} #${i + 1}`
  }));

  return (
    <div className="container mx-auto py-12 px-4">
      <h1 className="text-4xl font-bold mb-8 capitalize">
        {planet}
      </h1>

      <div className="mb-12">
        {/* Planet information... */}
      </div>

      <section>
        <div className="flex justify-between items-center mb-6">
          <h2 className="text-2xl font-bold">Gallery</h2>
          <Link
            href={`/destinations/${planet}/gallery`}
            className="text-indigo-600 hover:text-indigo-800"
          >
            View all
          </Link>
        </div>

        <div className="grid grid-cols-2 md:grid-cols-3 gap-4">
          {galleryImages.slice(0, 3).map(image => (
            <Link
              key={image.id}
              href={`/destinations/${planet}/gallery?image=${image.id}`}
              className="block aspect-square rounded-lg overflow-hidden"
            >
              <img
                src={image.src}
                alt={image.alt}
                className="w-full h-full object-cover hover:scale-105 transition-transform"
              />
            </Link>
          ))}
        </div>
      </section>
    </div>
  );
}
// app/destinations/[planet]/gallery/page.tsx - Full gallery
import Link from 'next/link';
import { notFound } from 'next/navigation';

export default async function GalleryPage({
  params,
  searchParams,
}: {
  params: Promise<{ planet: string }>;
  searchParams: Promise<{ image?: string }>;
}) {
  const { planet } = await params;
  const imageId = (await searchParams).image;

  // Verify that the planet exists
  const validPlanets = ['mars', 'europa', 'titan'];
  if (!validPlanets.includes(planet)) {
    notFound();
  }

  // Simulated gallery data
  const galleryImages = Array.from({ length: 12 }, (_, i) => ({
    id: i + 1,
    src: `/images/${planet}/${i + 1}.jpg`,
    alt: `Photo of ${planet} #${i + 1}`,
    title: `${planet.charAt(0).toUpperCase() + planet.slice(1)} - view #${i + 1}`
  }));

  return (
    <div className="container mx-auto py-12 px-4">
      <div className="flex items-center mb-8">
        <Link
          href={`/destinations/${planet}`}
          className="text-indigo-600 hover:underline mr-4"
        >
          โ† Back to {planet}
        </Link>
        <h1 className="text-3xl font-bold capitalize">
          Gallery: {planet}
        </h1>
      </div>

      <div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-4">
        {galleryImages.map(image => (
          <Link
            key={image.id}
            href={`/destinations/${planet}/gallery?image=${image.id}`}
            className="block aspect-square rounded-lg overflow-hidden"
          >
            <img
              src={image.src}
              alt={image.alt}
              className="w-full h-full object-cover hover:scale-105 transition-transform"
            />
          </Link>
        ))}
      </div>
    </div>
  );
}

The @modal slot reaches the layout of the [planet] segment as the modal prop, next to children. The default.tsx file says what to show in the slot while no modal is open:

// app/destinations/[planet]/layout.tsx - renders the page and the @modal slot
export default function PlanetLayout({
  children,
  modal,
}: {
  children: React.ReactNode;
  modal: React.ReactNode;
}) {
  return (
    <>
      {children}
      {modal}
    </>
  );
}
// app/destinations/[planet]/@modal/default.tsx - modal closed
export default function Default() {
  return null;
}

The modal itself reads params with the use() hook, because in Next.js 16 params is a Promise in a Client Component too:

// app/destinations/[planet]/@modal/(.)gallery/page.tsx - Gallery modal
'use client';

import { useRouter, useSearchParams } from 'next/navigation';
import { use, useEffect, useRef, useState } from 'react';

export default function GalleryModal({ params }: { params: Promise<{ planet: string }> }) {
  const router = useRouter();
  const searchParams = useSearchParams();
  const overlayRef = useRef(null);
  const { planet } = use(params);
  const imageId = searchParams.get('image');
  const [isClosing, setIsClosing] = useState(false);

  // Without ?image (the "View all" link) open the full gallery: a hard navigation skips the interception
  useEffect(() => {
    if (!imageId) {
      window.location.assign(`/destinations/${planet}/gallery`);
    }
  }, [imageId, planet]);

  // Handle ESC key
  useEffect(() => {
    const handleKeyDown = (e) => {
      if (e.key === 'Escape') {
        handleClose();
      }
    };

    window.addEventListener('keydown', handleKeyDown);
    return () => window.removeEventListener('keydown', handleKeyDown);
  }, []);

  const handleClose = () => {
    setIsClosing(true);
    setTimeout(() => {
      router.back();
    }, 300);
  };

  const handleOverlayClick = (e) => {
    if (e.target === overlayRef.current) {
      handleClose();
    }
  };

  if (!imageId) return null;

  // Get image data
  const imageIndex = parseInt(imageId) - 1;
  const galleryImages = Array.from({ length: 12 }, (_, i) => ({
    id: i + 1,
    src: `/images/${planet}/${i + 1}.jpg`,
    alt: `Photo of ${planet} #${i + 1}`,
    title: `${planet.charAt(0).toUpperCase() + planet.slice(1)} - view #${i + 1}`,
    description: `Detailed description of image #${i + 1} from planet ${planet}.`
  }));

  const image = galleryImages[imageIndex] || galleryImages[0];
  const prevImageId = image.id > 1 ? image.id - 1 : null;
  const nextImageId = image.id < galleryImages.length ? image.id + 1 : null;

  return (
    <div
      ref={overlayRef}
      onClick={handleOverlayClick}
      className={`fixed inset-0 z-50 bg-black/70 flex items-center justify-center p-4 transition-opacity duration-300 ${
        isClosing ? 'opacity-0' : 'opacity-100'
      }`}
    >
      <div
        className={`relative bg-white rounded-lg max-w-6xl w-full max-h-[90vh] overflow-hidden shadow-xl transition-transform duration-300 ${
          isClosing ? 'scale-95' : 'scale-100'
        }`}
        onClick={(e) => e.stopPropagation()}
      >
        <div className="flex h-full">
          <div className="w-2/3 bg-black flex items-center justify-center">
            <img
              src={image.src}
              alt={image.alt}
              className="max-h-[85vh] max-w-full object-contain"
            />
          </div>
          <div className="w-1/3 p-6 flex flex-col h-[85vh]">
            <button
              onClick={handleClose}
              className="absolute top-4 right-4 w-8 h-8 rounded-full flex items-center justify-center bg-gray-200 hover:bg-gray-300"
              aria-label="Close"
            >
              ร—
            </button>

            <h2 className="text-2xl font-bold mb-2">{image.title}</h2>
            <p className="text-gray-600 mb-6">{image.description}</p>

            <div className="mt-auto flex justify-between">
              {prevImageId ? (
                <button
                  onClick={() => router.replace(`/destinations/${planet}/gallery?image=${prevImageId}`)}
                  className="px-4 py-2 rounded border border-gray-300 hover:bg-gray-100"
                >
                  โ† Previous
                </button>
              ) : <div />}

              {nextImageId && (
                <button
                  onClick={() => router.replace(`/destinations/${planet}/gallery?image=${nextImageId}`)}
                  className="px-4 py-2 rounded border border-gray-300 hover:bg-gray-100"
                >
                  Next โ†’
                </button>
              )}
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

In this advanced example:

  1. When navigating to /destinations/mars/gallery?image=1, the page is intercepted by the modal
  2. The user can browse images in the modal without leaving the context of the main page
  3. After closing the modal, the user returns to the previous page without losing context

Parallel Routing

In the Quantum Metropolis, advanced Q-Links can split into two paths to simultaneously serve different destinations and then merge back together, optimizing urban transport flow. In Next.js 16, the equivalent of this technology is "Parallel Routing".

Basic Concept of Parallel Routes

Parallel routes in Next.js 16 enable rendering multiple pages or components in the same view, which is particularly useful for:

  1. Loading content in parallel with different priorities
  2. Independent navigation between multiple page components
  3. Creating complex layouts with multiple navigational regions

The implementation uses folders with the @ prefix:

app/
  โ”œโ”€โ”€ dashboard/
  โ”‚   โ”œโ”€โ”€ layout.tsx            # Page layout
  โ”‚   โ”œโ”€โ”€ page.tsx              # Main content
  โ”‚   โ”œโ”€โ”€ @stats/               # "stats" Slot
  โ”‚   โ”‚   โ”œโ”€โ”€ page.tsx          # Default page in "stats" slot
  โ”‚   โ”‚   โ””โ”€โ”€ default.tsx       # Required since Next.js 16
  โ”‚   โ””โ”€โ”€ @activity/            # "activity" Slot
  โ”‚       โ”œโ”€โ”€ page.tsx          # Default page in "activity" slot
  โ”‚       โ””โ”€โ”€ default.tsx       # Required since Next.js 16

Since Next.js 16, every slot needs its own default.tsx file - without it, next build fails. Next.js shows this file when it cannot match the slot's page to the current address, for example after a browser refresh on a subpage. The simplest version renders nothing:

// app/dashboard/@stats/default.tsx
export default function Default() {
  return null;
}

This file changes nothing in how the page looks, but it satisfies the Next.js 16 requirement. If you would rather show a 404 page in this situation, call notFound() in it.

Example: Space Travel Agency Dashboard

Implementation:

// app/dashboard/layout.tsx - Layout with parallel routes
export default function DashboardLayout({
  children,   // Main content
  stats,      // @stats Slot
  activity    // @activity Slot
}) {
  return (
    <div className="container mx-auto px-4 py-8">
      <h1 className="text-3xl font-bold mb-8">Quantum Voyages Control Panel</h1>

      <div className="grid grid-cols-12 gap-8">
        {/* Main content */}
        <div className="col-span-12 lg:col-span-6">
          {children}
        </div>

        {/* Statistics panel */}
        <div className="col-span-12 md:col-span-6 lg:col-span-3">
          <div className="bg-white shadow rounded-lg p-4 h-full">
            {stats}
          </div>
        </div>

        {/* Activity panel */}
        <div className="col-span-12 md:col-span-6 lg:col-span-3">
          <div className="bg-white shadow rounded-lg p-4 h-full">
            {activity}
          </div>
        </div>
      </div>
    </div>
  );
}
// app/dashboard/page.tsx - Main content
export default function DashboardPage() {
  return (
    <div className="bg-white shadow rounded-lg p-6">
      <h2 className="text-2xl font-semibold mb-4">Booking Overview</h2>

      <div className="space-y-6">
        <div className="p-4 border rounded-lg">
          <h3 className="font-semibold">Upcoming Trip</h3>
          <p className="mt-2">Mars - Colony Alpha, June 12, 2150</p>
          <div className="mt-4 flex justify-between">
            <span className="text-indigo-600">Status: Confirmed</span>
            <button className="text-sm text-indigo-600 hover:underline">
              Details
            </button>
          </div>
        </div>

        <div className="p-4 border rounded-lg">
          <h3 className="font-semibold">Travel History</h3>
          <ul className="mt-2 space-y-2">
            <li className="flex justify-between">
              <span>Europa - Research Station</span>
              <span>March 24, 2150</span>
            </li>
            <li className="flex justify-between">
              <span>Moon - Armstrong Base</span>
              <span>January 12, 2150</span>
            </li>
          </ul>
        </div>

        <div className="p-4 border rounded-lg">
          <h3 className="font-semibold">Recommended Destinations</h3>
          <ul className="mt-2 space-y-2">
            <li>
              <a href="/destinations/titan" className="text-indigo-600 hover:underline">
                Titan - newly opened colonies
              </a>
            </li>
            <li>
              <a href="/destinations/venus-orbiter" className="text-indigo-600 hover:underline">
                Venus Orbiter - scientific stay
              </a>
            </li>
          </ul>
        </div>
      </div>
    </div>
  );
}
// app/dashboard/@stats/page.tsx - Statistics
export default function StatsPage() {
  // In a real application, this data would be fetched from the API
  const stats = [
    { label: 'Total Flights', value: '7' },
    { label: 'Visited Planets', value: '3' },
    { label: 'Loyalty Points', value: '12,540' },
    { label: 'Member Status', value: 'Gold' }
  ];

  return (
    <div>
      <h2 className="text-xl font-semibold mb-4">Travel Statistics</h2>

      <div className="space-y-4">
        {stats.map((stat, index) => (
          <div key={index} className="flex justify-between">
            <span className="text-gray-600">{stat.label}:</span>
            <span className="font-semibold">{stat.value}</span>
          </div>
        ))}
      </div>

      <div className="mt-6 pt-4 border-t">
        <div className="flex justify-between items-center">
          <span className="text-gray-600">Next status level:</span>
          <span className="text-sm font-medium">Platinum</span>
        </div>
        <div className="mt-2 w-full bg-gray-200 rounded-full h-2.5">
          <div className="bg-indigo-600 h-2.5 rounded-full" style={{ width: '70%' }}></div>
        </div>
        <p className="mt-1 text-xs text-right text-gray-500">7,460 points to next level</p>
      </div>
    </div>
  );
}
// app/dashboard/@activity/page.tsx - Activity
export default function ActivityPage() {
  // In a real application, this data would be fetched from the API
  const activities = [
    { type: 'reservation', message: 'You booked a trip to Mars', time: '2 hours ago' },
    { type: 'check-in', message: 'Online check-in completed for flight QV-105', time: '3 days ago' },
    { type: 'payment', message: 'Payment of 12,500 CR completed', time: '1 week ago' },
    { type: 'review', message: 'You wrote a review for Armstrong Base', time: '2 weeks ago' }
  ];

  return (
    <div>
      <h2 className="text-xl font-semibold mb-4">Recent Activity</h2>

      <div className="space-y-4">
        {activities.map((activity, index) => (
          <div key={index} className="flex items-start">
            <div className={`mt-1 rounded-full w-2 h-2 mr-2 ${
              activity.type === 'reservation' ? 'bg-green-500' :
              activity.type === 'check-in' ? 'bg-blue-500' :
              activity.type === 'payment' ? 'bg-purple-500' :
              'bg-yellow-500'
            }`}></div>
            <div>
              <p className="text-sm">{activity.message}</p>
              <p className="text-xs text-gray-500">{activity.time}</p>
            </div>
          </div>
        ))}
      </div>

      <div className="mt-6 flex justify-center">
        <button className="text-sm text-indigo-600 hover:underline">
          View all activities
        </button>
      </div>
    </div>
  );
}

This example demonstrates how parallel routes enable creating complex layouts where different parts of the page can be independently updated and loaded.

Summary

Just as the advanced transportation system in the Quantum Metropolis enables residents to move smoothly between different parts of the city, navigation in Next.js 16 offers developers and users an extremely efficient and intuitive system for moving through the application.

Key elements of navigation in Next.js 16:

  1. Link Component - the fundamental navigation element that enables fast transitions between pages without a full reload, thanks to automatic prefetching and optimizations.

  2. useRouter - a hook enabling programmatic navigation, ideal for dynamically directing users based on specific conditions or events.

  3. usePathname and useSearchParams - hooks for monitoring the current path and query parameters, enabling reactive UI adjustments.

  4. Intercepting Routes - an advanced feature allowing navigation interception to specific paths and displaying alternative UI, often in the form of a modal.

  5. Parallel Routing - enables rendering multiple pages or components in a single view, ideal for complex dashboards and interfaces with multiple navigational regions.

These tools, used together, enable creating efficient, intuitive, and advanced navigation systems that significantly improve user experience and application performance.

In the next chapter, we will explore route grouping and organization techniques that help maintain order and structure in more complex applications, just as zone planning in the Quantum Metropolis helps keep the city organized and efficient.

Docs entries used in this lesson

Spotted a mistake in this lesson?

Useful articles