Understanding Nested Routes in React Router

Understanding the Problem

When building a React application with nested content, like a movie library where clicking a movie title should show its details within the same page, we need a way to manage these nested views. Think of it like opening a book (the main movies page) and then flipping to a specific chapter (the movie details) - both the book and chapter are visible at the same time. We need to:

Planning Our Solution

  1. Set up the parent Movies component with a list of movies
  2. Create a nested route structure for showing movie details
  3. Build a navigation bar to switch between different movies
  4. Use URL parameters to track and display the selected movie
  5. Implement the movie details display using the parameter data

Basic Implementation

Let's look at our file structure first:

src/
  ├── App.jsx
  ├── data/
  │   └── movieData.js
  └── components/
      └── Movies/
          ├── Movies.jsx
          ├── MovieNavBar.jsx
          └── MovieDetails.jsx

Step 1: Setting Up the Router (App.jsx)

// App.jsx
import { createBrowserRouter, RouterProvider } from 'react-router-dom';
import Movies from './components/Movies';
import MovieDetails from './components/Movies/MovieDetails';
import { movies } from './data/movieData';

// Create our router with nested routes
const router = createBrowserRouter([
  {
    path: '/movies',
    // Pass movies data as a prop to the Movies component
    element: <Movies movies={movies} />,
    // Define the nested route for movie details
    children: [
      {
        // :movieId is a dynamic parameter that will change based on selected movie
        path: ':movieId',
        element: <MovieDetails movies={movies} />
      }
    ]
  }
  // ... other routes
]);

Step 2: Creating the Movies Component with Outlet

// Movies/Movies.jsx
import { Outlet } from 'react-router-dom';
import MovieNavBar from './MovieNavBar';

function Movies({ movies }) {
  return (
    <div>
      <h1>Movies Component</h1>
      {/* MovieNavBar shows the list of clickable movie titles */}
      <MovieNavBar movies={movies} />
      {/* Outlet is where the MovieDetails component will render */}
      <Outlet />
    </div>
  );
}

Step 3: Building the Movie Navigation Bar

// Movies/MovieNavBar.jsx
import { NavLink } from 'react-router-dom';

function MovieNavBar({ movies }) {
  return (
    <nav>
      {movies.map(movie => (
        <NavLink
          key={movie.id}
          to={`${movie.id}`}  // Creates relative path like /movies/1
          className={({ isActive }) => 
            isActive ? 'active-movie' : ''
          }
        >
          {movie.title}
        </NavLink>
      ))}
    </nav>
  );
}

Step 4: Creating the Movie Details Component

// Movies/MovieDetails.jsx
import { useParams } from 'react-router-dom';

function MovieDetails({ movies }) {
  // Get the movieId from the URL parameter
  const { movieId } = useParams();
  
  // Find the selected movie from our movies array
  const movieChoice = movies.find(
    movie => movie.id === parseInt(movieId)
  );

  // If no movie is found, show an error message
  if (!movieChoice) {
    return <h2>Movie not found!</h2>;
  }

  return (
    <div>
      <h1>{movieChoice.title}</h1>
      <p>{movieChoice.description}</p>
    </div>
  );
}

Understanding Through Analogies

Think of nested routes like a library organization system:

Common Challenges and Solutions

Here are some typical issues new developers face when working with nested routes:

Challenge 1: Nothing Shows in the Nested Route

If you're not seeing the nested content, check that:

Challenge 2: Parameter Type Mismatches

Remember that URL parameters are always strings. When comparing with numeric IDs:

Testing Your Implementation

To verify your nested routing is working correctly:

  1. Visit the main movies page - should see the list of movies
  2. Click a movie title - URL should update with the movie ID
  3. Movie details should appear below the list
  4. Clicking different movies should update both URL and details
  5. Refreshing the page should maintain the selected movie

Real World Applications

This nested routing pattern is commonly used in:

Practice Exercises

To better understand nested routes, try these challenges:

  1. Add a nested comments section for each movie
  2. Create multiple levels of nesting (e.g., genres → movies → details)
  3. Add loading states while fetching movie details
  4. Implement error boundaries for missing movies

Debugging Tips

When troubleshooting nested routes, remember to: