Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

Sorry, you do not have permission to ask a question, You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please type your username.

Please type your E-Mail.

Please choose an appropriate title for the post.

Please choose the appropriate section so your post can be easily searched.

Please choose suitable Keywords Ex: post, video.

Browse

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Logo Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Logo

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Navigation

  • Home
  • About Us
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • About Us
  • Contact Us
Home/ Questions/Q 6359

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Latest Questions

Author
  • 60k
Author
Asked: November 27, 20242024-11-27T05:49:09+00:00 2024-11-27T05:49:09+00:00

How to implement nested routes with React Router

  • 60k

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.

beginnersreactwebdev
  • 0 0 Answers
  • 2 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

Sidebar

Ask A Question

Stats

  • Questions 4k
  • Answers 0
  • Best Answers 0
  • Users 2k
  • Popular
  • Answers
  • Author

    ES6 - A beginners guide - Template Literals

    • 0 Answers
  • Author

    Understanding Higher Order Functions in JavaScript.

    • 0 Answers
  • Author

    Build a custom video chat app with Daily and Vue.js

    • 0 Answers

Top Members

Samantha Carter

Samantha Carter

  • 0 Questions
  • 20 Points
Begginer
Ella Lewis

Ella Lewis

  • 0 Questions
  • 20 Points
Begginer
Isaac Anderson

Isaac Anderson

  • 0 Questions
  • 20 Points
Begginer

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help

Footer

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise

Querify Question Shop: Explore, ask, and connect. Join our vibrant Q&A community today!

About Us

  • About Us
  • Contact Us
  • All Users

Legal Stuff

  • Terms of Use
  • Privacy Policy
  • Cookie Policy

Help

  • Knowledge Base
  • Support

Follow

© 2022 Querify Question. All Rights Reserved

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.