
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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.
Advertisements