How to implement nested routes with React Router
Tags: react, webdev, beginners
Published: 2021-05-11 03:37:30

[In the last article](https://dev.to/junko911/implementing-client-side-routing-with-react-router-5bc5), I walked through how to implement client-side routes using [React Router](https://reactrouter.com/). 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`:
```jsx
// 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
```
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:
```jsx
// 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
```
![Link](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/lom3upx5hqfp0bmpybk8.png)
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:
```jsx
// 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
```
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>`:
```jsx
// 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
```
Let's see what is happening here.

First, you need to put the most specific routes first as I explained in [the last article](https://dev.to/junko911/implementing-client-side-routing-with-react-router-5bc5).

Second, what is `match`? When rendering a component through a `<Route>`, the function accepts an argument called [route props](https://reactrouter.com/web/api/Route/route-props). The route props include `match`, `location`, and `history`. The [`match`](https://reactrouter.com/web/api/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:
```jsx
<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} />
        }} />
```
![Console](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/dxvqoy8xvye2xs6zq81c.png)
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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qoexmm6z6q2pa20q33be.png)
***
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.