Nested Routing in React.js


We have an app.jsx component

import React, { Component } from 'react';
import { Link, Route, Switch } from 'react-router-dom';
import Category from './Category';
class App extends Component {
   render() {
      return (
         <div>
            <nav className="navbar navbar-light">
               <ul className="nav navbar-nav">
                  <li><Link to="/">Main Page</Link></li>
                  <li><Link to="/users">Users</Link></li>
               </ul>
            </nav>
            <Switch>
               <Route exact path="/" component={MainPage}/>
               <Route path="/users" component={Users}/>
            </Switch>
         </div>
      );
   }
}
export default App;

We have two components here MainPage and Users. MainPage is our main component which is mapped using exact keyword and path as ‘/’

The User component is where we will have the nested routing. The actual nesting will be implemented inside the Users component. Here in app.jsx file we will have only the parent link to the Users component.

Nesting in Users component

import React from 'react';
import { Link, Route } from 'react-router-dom';
const Users = ({ match }) => {
   return(
      <div>
         <ul>
            <li><Link to={`${match.url}/David`}>David</Link></li>
            <li><Link to={`${match.url}/Steve`}>Steve</Link></li>
            <li><Link to={`${match.url}/John`}>John</Link></li>
         </ul>
         <Route path={`${match.path}/:name`} render= {({match}) =>( <div><h3> {match.params.name} </h3></div>)}/>
      </div>
   )
}
export default Users;

The match object contains the path /users and :name attribute contains the nesting for particular user. We have also created the Link components in Users for navigating to specific users.

Note the use of render attribute on Route path in Users component. Render is executing the function to display user.

Updated on: 04-Sep-2019

328 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements