DEV Community

Junko T.
Junko T.

Posted on • Updated on

How to implement nested routes with React Router

In the last article, I walked through how to implement client-side routes using React Router. What if we have a list of items and want to create a detail page for each item? Should we create paths like:

https://example.com/movies/1,
https://example.com/movies/2,
https://example.com/movies/3,

and so on?

No, we, web developers, are too lazy to hard-code. With React Router, you can create nested routes with parameters.

React Router uses nested routes to render more specific routing information inside of child components. We can make each item in a list clickable, so, when one item is clicked, the details page of the item will be displayed. And, by setting parameters, we could set routes for details pages dynamically.

I prepared movies data in App.js. Let's create MovieList page and MoveDetails page under it and set up nested routes.

Add links using <Link>

First, let's create <MovieList> component and render it in App.js:

// myapp/src/components/MovieList.js

import React from 'react'
import { Link } from 'react-router-dom'

const MovieList = ({ movies }) => {
  return (
    <>
      <h1>Movie List</h1>
      <ul>
        {movies.map(movie => {
          return (
            <li key={movie.id}>
              <Link to={`/movies/${movie.id}`}>
                {movie.title}
                  </Link>
            </li>
           )
         })}
      </ul>
    </>
  )
}

export default MovieList
Enter fullscreen mode Exit fullscreen mode

The <Link> component renders an anchor tag that navigates to different a route defined in the application. There is also <NavLink> you can use when you want to add styling.

We will render <MovieList> component in App.js and pass movies data to it as props:

// myapp/src/App.js

import React from 'react'
import { BrowserRouter, Route, Switch } from 'react-router-dom'
import Home from "./components/Home"
import Contact from './components/Contact'
import AboutUs from './components/AboutUs'
import MovieList from './components/MovieList'

const App = () => {

  const movies = [
    { id: 1, title: 'Clockwork Orange', year: '1971' },
    { id: 2, title: 'Full Metal Jacket', year: '1987' },
    { id: 3, title: 'The Shining', year: '1980' },
    { id: 4, title: '2001: A Space Odyssey', year: '1968' }
  ]

  return (
    <>
      <h1>My App</h1>
      <BrowserRouter>
        <Switch>
          <Route path="/home/about" component={AboutUs} />
          <Route path="/home" component={Home} />
          <Route exact path="/contact" component={Contact} />
          <Route path="/movies" render={() => <MovieList movies={movies} />} />
        </Switch>
      </BrowserRouter>
    </>
  )
}

export default App
Enter fullscreen mode Exit fullscreen mode

Link
Now we got a list of links in the <MovieList> page, and, if you click one of the items, you will see the id of the item added at the end of the URL, like http://localhost:3000/movies/1, as we defined.

Add nested routes with parameters using route props

Let's create <MovieDetails> component:

// myapp/src/components/MovieDetails.js

import React from 'react'

const MovieDetails = ({ movie }) => {
  return (
    <>
      {movie ?
        <>
          <h1>Movie Details</h1>
          <p>Title: {movie.title}</p>
          <p>Year: {movie.year}</p>
        </>
        :
        <p>No movie found.</p>
      }
    </>
  )
}

export default MovieDetails
Enter fullscreen mode Exit fullscreen mode

It expects movie prop to be passed from the parent component. Now, let's go back to the <MovieList> component.

We want the paths to be like /movies/1, /movies/2. Whatever comes after /movies, we will define it in <MovieList> component. For that, we need React Router <Switch> and <Route>:

// myapp/src/components/MovieList.js

import React from 'react'
import { Switch, Route, Link } from 'react-router-dom'
import MovieDetails from './MovieDetails'

const MovieList = ({ movies }) => {
  return (
    <>
      <Switch>
        <Route path="/movies/:id" render={({ match }) => {
          const id = parseInt(match.params.id)
          const foundMovie = movies.find(movie => movie.id === id)
          return <MovieDetails movie={foundMovie} />
        }} />
        <Route path="/movies" render={() => {
          return (
            <>
              <h1>Movie List</h1>
              <ul>
                {movies.map(movie => {
                  return (
                    <li key={movie.id}>
                      <Link to={`/movies/${movie.id}`}>
                        {movie.title}
                      </Link>
                    </li>
                  )
                })}
              </ul>
            </>
          )
        }} />
      </Switch>
    </>
  )
}

export default MovieList
Enter fullscreen mode Exit fullscreen mode

Let's see what is happening here.

First, you need to put the most specific routes first as I explained in the last article.

Second, what is match? When rendering a component through a <Route>, the function accepts an argument called route props. The route props include match, location, and history. The match object contains information about how a <Route path> matched the URL.

If you add an argument to render prop and console.log() it, you can see the actual route props:

<Route path="/movies/:id" render={routeProps => {
  console.log(routeProps)
  const id = parseInt(routeProps.match.params.id)
  const foundMovie = movies.find(movie => movie.id === id)
  return <MovieDetails movie={foundMovie} />
        }} />
Enter fullscreen mode Exit fullscreen mode

Console
The match object has properties including params. As we call the parameter :id, we can get the value from the URL by match.params.id.

Lastly, use .find method to find movie by id and pass it to <MovieDetails> component.

Movie details


Using React Router, you can use routes to separate your single page application into usable pieces. It is important for letting users access different pages easily and consistently.

Top comments (0)