Nested Routing in React.js

React JSJavascript LibraryFront End Technology

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 (
            <nav className="navbar navbar-light">
               <ul className="nav navbar-nav">
                  <li><Link to="/">Main Page</Link></li>
                  <li><Link to="/users">Users</Link></li>
               <Route exact path="/" component={MainPage}/>
               <Route path="/users" component={Users}/>
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 }) => {
            <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>
         <Route path={`${match.path}/:name`} render= {({match}) =>( <div><h3> {} </h3></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 11:30:19