Routing in React using React-Router: Part2

Manav Pandya   Source Code  Print 
19 Sep 2018
22 Sep 2018
Intermediate
200

In our previous article, we have developed simple routing mechanism where we can traverse through different URLs of the application, the same way if we have tons of pages into the application so in this case, the situation will be more complex to handle.For that, we can develop child routing or you can say nested routing in react application. To implement child or nested routing, in this article we will learn a simple approach for that.

In this part of react router series, I have used few of the same package as we have used previously in React Routing Part1, so I am just going to modify those files to implement our nested routing functionality. In this article, I have used many react-bootstrap components which are listed below.

  • Navbar

  • Nav

  • Panel

  • So these are some primary components I have used to design a user interface, now let’s see the steps to configure nested routing.

Steps to configure nested/child routing

To implement nested or child routes, we need to follow few steps to implement the functionality.

Step 1

Previously, we have created three primary files named

Home.js
 import React from 'react';
 
 const Home = () => (
 <div>
 <h1>This Is From Dashboard Page</h1>
 </div>
 )
 
 export default Home;
About.js
 import React from 'react';
 
 const About = () => (
 <div>
 <h1>This Is From About Us Page</h1>
 </div>
 )
 
 export default About;
Contact.js

So in this file, we are actually implementing child or nested routes, open the file and paste below code snippet.

 import React from 'react';
 import Profile from './child/Profile';
 import Email from './child/Email';
 import Phone from './child/Phone';
 
 import { Tabs, Tab, Panel } from 'react-bootstrap';
 // To use routing functionalities
 import { Link, Switch, Route } from 'react-router-dom';
 
 const divStyle = {
 width: '50%',
 margin: '7px 27%'
 };
 const Contact = (match) => (
 <div>
 <h1>This is From Contact US Page</h1><hr />
 
 <Link to="/contact">Profile</Link> |
 <Link to="/contact/email">Email</Link> |
 <Link to="/contact/phone">Phone Number</Link>
 
 <Switch>
 <Route exact path='/contact' component={Profile} />
 <Route exact path='/contact/email' component={Email} />
 <Route exact path='/contact/phone' component={Phone} />
 </Switch>
 </div>
 )
 
 export default Contact;

As you can see that in contact us page, I have also included <link> to apply child components to be rendered and same as Switch will allow us to render appropriate user interface matching with the requested URL. Apart from these three files, we can create more file to see the functionality for a child or nested routing, for that create another three more files inside a new folder named Child.

/components/child/Profile.js
 import React from 'react';
 import { Tabs, Tab, Panel } from 'react-bootstrap';
 
 const divStyle = {
 width: '50%',
 margin: '7px 27%'
 };
 
 const Profile = () => (
 <div>
 <Panel style={divStyle}>
 Ubgifu79bg79 <Panel.Heading>Profile Page </Panel.Heading>
 <Panel.Body><a href="https://www.dotnettricks.com/mentor/manav">Click Here</a></Panel.Body>
 </Panel>
 </div>
 )
 
 export default Profile;
/components/child/Email.js
 import React from 'react';
 import { Tabs, Tab, Panel } from 'react-bootstrap';
 
 const divStyle = {
 width: '50%',
 margin: '7px 27%'
 };
 
 const Email = () => (
 <div>
 <Panel style={divStyle}>
 <Panel.Heading>Email</Panel.Heading>
 <Panel.Body>pandya.manav@gmail.com</Panel.Body>
 </Panel>
 </div> 
 )
 
 export default Email;
/components/child/Phone.js
 import React from 'react';
 import { Tabs, Tab, Panel } from 'react-bootstrap';
 
 const divStyle = {
 width: '50%',
 margin: '7px 27%'
 };
 
 const Phone = () => (
 <div>
 <Panel style={divStyle}>
 <Panel.Heading>Contact</Panel.Heading>
 <Panel.Body>1234567891</Panel.Body>
 </Panel>
 </div>
 )
 
 export default Phone;

All above three of the file just containing static data, and as you can observe that here in these files, I have used Panel component of react-bootstrap.

Step 2

If you have followed previous part of this series then we have developed primary routing into an app.js file which is the main component for our web application, Apart from the routing part, as you can see that I have used additional components which is react-bootstrap. This is used to design our layout. Open app.js and paste the following code snippet.

App.js
 import React, { Component } from 'react';
 import './App.css';
 
 // ract-bootstrap components
 import { Navbar, Nav, NavItem, MenuItem, NavDropdown , Tabs , Tab } from 'react-bootstrap';
 
 // Our speperately created components
 import Home from './Components/Home';
 import About from './Components/About';
 import Contact from './Components/Contact';
 
 // To use routing functionalities
 import { Link, Switch, Route } from 'react-router-dom';
 
 class App extends Component {
 render() {
 return (
 <div className="App">
 <Navbar>
 <Navbar.Header>
 <Navbar.Brand>
 <a>Routing With React-Router Part-2</a>
 </Navbar.Brand>
 </Navbar.Header>
 <Nav>
 <NavItem href="javascript:void(0)">
 <Link to="/">Dashboard</Link>
 </NavItem>
 <NavItem href="javascript:void(0)">
 <Link to="/about">About Us</Link>
 </NavItem>
 <NavItem href="javascript:void(0)">
 <Link to="/contact">Contact Us</Link>
 </NavItem>
 </Nav>
 </Navbar>
 <Switch>
 <Route exact path='/' component={Home} />
 <Route path='/about' component={About} />
 <Route path='/contact' component={Contact} />
 </Switch>
 </div>
 );
 }
 }
 
 export default App;

Step 3

So far, we have covered our user interface part, but let me clarify one thing that if you execute above example then it would not work because we have not implemented BrowserRouter to our main component which is index.js.

What is BrowserRouter

When we are working with the router in react, in the background it manages history API of HTML5, I mean when we routing through different pages that that time we should maintain history so that components will be available to route back again. Basically, it manages three different events which are listed below.

  • pushState

  • popState

  • replaceState

  • These events are used to manage the different routing activity using state and update accordingly based on the history object.

To configure BrowserRouter, we need to import the API from the package react-router-dom like this.

 import { BrowserRouter } from 'react-router-dom';

After the completion of the BrowserRouter configuration the final index.js file looks like this.

 import React from 'react';
 import ReactDOM from 'react-dom';
 import './index.css';
 import App from './App';
 import registerServiceWorker from './registerServiceWorker';
 import { BrowserRouter } from 'react-router-dom';
 
 ReactDOM.render(
 <BrowserRouter>
 <App />
 </BrowserRouter>, document.getElementById('root'));
registerServiceWorker();

Note

Before executing the project, make sure to update index.html file like this.

 <!DOCTYPE html>
 <html lang="en">
 
 <head>
 <meta charset="utf-8">
 <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
 <meta name="theme-color" content="#000000">
 <link rel="manifest" href="%PUBLIC_URL%/manifest.json">
 <link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico">
 <!-- Bootstrap CDN Files -->
 <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u"
 crossorigin="anonymous">
 <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp"
 crossorigin="anonymous">
 <!-- End -->
 <title>React App</title>
 </head>
 
 <body>
 <noscript>
 You need to enable JavaScript to run this app.
 </noscript>
 <div id="root"></div>
 </body>
 
 </html>

Because it contains the two different style sheets which are responsible for all the themes related setting if you omit those style sheets than it is may possible that you cannot see the output in a proper manner.Our last step is to execute the application and see that how nested/child routing works.

Output

  • Dashboard Page
  • This page is the entry point of our application.

  • About Us Page
  • Contact US (With profile page as a child)
  • Here in this page, we have implemented child/nested routes, when we click on the contact link at that time it by default loads the profile page because we are told them to do so.

  • Email Details Page
  • When you click on the email link, at that time just observer the URL that how child key was added to the URL.

  • Phone Number Details Page
  • This is the contact us page where we have printed the contact number details.

If you look at all above pages, from the contact pages we have three separate child routes and whenever we click on appropriate links at that time it loads the only content of child and replaces with the existing one.This Is how we can achieve child/nested routing, but keep in mind that it does not follow any standard, it’s just only for practice purpose thus you can try and implement it by following the proper standard.

Summary

In this two-part of the series using react-router, we have covered so many concepts with bootstrap components, let’s recap it quickly.

  • Introduction to routing

  • Packages to use for routing

  • Steps to configure simple routing

  • Steps to configure child/nested routing

  • How to use bootstrap components with react

  • I hope you have learned something from these two part of series, I have shared the source code with this article and try to implement all the feature that we have covered and apply it to your project.

Hands-on Learning
Free Interview Books
 
+