Introduction to Routing in React

Introduction

 
In the previous articles, we have learned about Redux integration with React. Now we will learn about Routing in React. In this article, we will learn what is React routing and how it can be implemented in our application.
 

React Router

 
React router is a routing library built on top of the react used to create the routing in react apps.
 
Initially React router v4 was static.  After React router v4 routings are dynamic. While using single-page applications, the single HTML page is used and multiple components are re-rendered in routing, but while using multiple pages in the application an entirely new page is re-rendered.
 

Setup React Router

 
To create a routing application, we need a command named
  1. npx create-react-app routingapp  
 
 
After successful creation of react application, change your folder path to your application
  1. cd routingapp  
and after that, we will install a react-router package to start using it in our application.
  1. npm install react-router-dom  
 
 
After the successful installation of the above package, now we will create 2 components named Home and ContactUs.
 
Home.js
  1. import React, { Component } from 'react'  
  2.   
  3. export class Home extends Component {  
  4.     render() {  
  5.         return (  
  6.             <div>  
  7.                 Home Component  
  8.             </div>  
  9.         )  
  10.     }  
  11. }  
  12.   
  13. export default Home  
ContactUs.js
  1. import React, { Component } from 'react'  
  2.   
  3. export class ContactUs extends Component {  
  4.     render() {  
  5.         return (  
  6.             <div>  
  7.                 Contact Us Component  
  8.             </div>  
  9.         )  
  10.     }  
  11. }  
  12.   
  13. export default ContactUs  
There are two types of routers in React

  1. BrowserRouter - When your application needs to handle dynamic requests than BrowserRouter is used.
  2. HashRouter - When static request needs to be handled by your application then HashRouter is used.
The React router provides three components, Route, Link, BrowserRouter which help in the routing of the component.
 
Let’s implement routing in App.js. For that first, we need to import component from react Router along with our custom-created component,
  1. import { Route, Link, BrowserRouter as Router } from 'react-router-dom'  
  2.   
  3. import Home from './components/Home';  
  4.   
  5. import ContactUs from './components/ContactUs';   
After importing we will define <Router> component under which we will link our component using <Link> Component and define route using <Route> component as below,
  1. <Router>  
  2.       <div className="App">  
  3.         <nav className="navbar navbar-expand-lg navbar-light bg-light">  
  4.           <ul className="navbar-nav mr-auto">  
  5.             <li><Link to={'/'} className="nav-link"> Home </Link></li>  
  6.             <li><Link to={'/ContactUs'} className="nav-link">Contact Us</Link></li>  
  7.             
  8.           </ul>  
  9.         </nav>  
  10.         <hr />  
  11.           <Route exact path="/" component={Home} />  
  12.           <Route path="/" component={ContactUs} />  
  13.       </div>  
  14. </Router>   
Now the whole component will look like as below,
  1. import React from 'react';  
  2. import { Route, Link, BrowserRouter as Router } from 'react-router-dom'  
  3. import './App.css';  
  4. import Home from './components/Home';  
  5. import ContactUs from './components/ContactUs';  
  6.   
  7. function App() {  
  8.   return (  
  9.     <Router>  
  10.       <div className="App">  
  11.         <nav className="navbar navbar-expand-lg navbar-light bg-light">  
  12.           <ul className="navbar-nav mr-auto">  
  13.             <li><Link to={'/'} className="nav-link"> Home </Link></li>  
  14.             <li><Link to={'/ContactUs'} className="nav-link">Contact Us</Link></li>  
  15.             
  16.           </ul>  
  17.         </nav>  
  18.         <hr />  
  19.           <Route exact path="/" component={Home} />  
  20.           <Route path="/" component={ContactUs} />  
  21.       </div>  
  22.     </Router>  
  23.   );  
  24. }  
  25.   
  26. export default App;   
Now we will create another file named main.js,
  1. import React from 'react'  
  2. import App from './App'  
  3.   
  4. function main() {  
  5.     return (  
  6.         <div>  
  7.             <App></App>  
  8.         </div>  
  9.     )  
  10. }  
  11.   
  12. export default main   
Now after running the application, it will look like below,
 
 
In Route component, it accepts 2 parameters:
 
path: It requires the path of the component
component: It accepts the name of the component needed for navigation.
 
Now let’s think of a case where the URL for which a user wants to navigate does not found. In that case, we need to implement a 404 not found page.
 

What is 404 Page and how it can be implemented?

 
A 404-page also called as Not found page which is required whenever the user navigates to a wrong page or the page that does not exist. In that case, the user is shown a Not found page.
 
To add a 404 page in React, we will need another component named Switch.
 
Switch component helps us to render the component only when path found else it will go to not found component.
 
To create a not found component, we will create a notfound.js component,
  1. import React from 'react'  
  2.   
  3. const NotFound = () => <h1>Page Not Found</h1>  
  4.   
  5. export default NotFound   
Now import in App.js,
  1. import React from 'react';  
  2. import { Route, Link, Switch, BrowserRouter as Router } from 'react-router-dom'  
  3. import './App.css';  
  4. import Home from './components/Home';  
  5. import ContactUs from './components/ContactUs';  
  6. import NotFound from './components/notfound';  
  7. function App() {  
  8.   return (  
  9.     <Router>  
  10.       <div>  
  11.         <nav className="navbar navbar-expand-lg navbar-light bg-light">  
  12.           <ul className="navbar-nav mr-auto">  
  13.             <li><Link to={'/'} className="nav-link"> Home </Link></li>  
  14.             <li><Link to={'/ContactUs'} className="nav-link">Contact Us</Link></li>  
  15.           </ul>  
  16.         </nav>  
  17.         <hr />  
  18.         <Switch>  
  19.           <Route exact path="/" component={Home} />  
  20.           <Route path="/contactus" component={ContactUs} />  
  21.           <Route component={NotFound} />  
  22.         </Switch>  
  23.       </div>  
  24.     </Router>  
  25.   );  
  26. }  
  27.   
  28. export default App;   
and the output will be displayed as, hit the link, http://localhost:3000/users
 
 
as we know the user component does not exist so it will display a 404 page.
 

URL Parameters

 
Url parameters are used to render the same components along with dynamic url. Just as passing name in ContactUs component like below,
  1. <Route path="/contactus/:name" component={ContactUs} />   
App.js
  1. import React from 'react';  
  2. import { Route, Link, Switch, BrowserRouter as Router } from 'react-router-dom'  
  3. import './App.css';  
  4. import Home from './components/Home';  
  5. import ContactUs from './components/ContactUs';  
  6. import NotFound from './components/notfound';  
  7. function App() {  
  8.   return (  
  9.     <Router>  
  10.       <div>  
  11.         <nav className="navbar navbar-expand-lg navbar-light bg-light">  
  12.           <ul className="navbar-nav mr-auto">  
  13.             <li><Link to={'/'} className="nav-link"> Home </Link></li>  
  14.             <li><Link to={'/ContactUs'} className="nav-link">Contact Us</Link></li>  
  15.           </ul>  
  16.         </nav>  
  17.         <hr />  
  18.         <Switch>  
  19.           <Route exact path="/" component={Home} />  
  20.           <Route path="/contactus/:name" component={ContactUs} />  
  21.           <Route component={NotFound} />  
  22.         </Switch>  
  23.       </div>  
  24.     </Router>  
  25.   );  
  26. }  
  27.   
  28. export default App;   
Now in contactus.js, update the code as below,
  1. import React, { Component } from 'react'  
  2.   
  3. export class ContactUs extends Component {  
  4.     render() {  
  5.         console.log(this.props)  
  6.         return (  
  7.             <div>                  
  8.                 Contact Us Component  
  9.             </div>  
  10.         )  
  11.     }  
  12. }  
  13.   
  14. export default ContactUs   
The output will be displayed in the console,
 
 
Here in the console, we can see that this.prop has multiple objects so to access the properties from this.props.match.
  1. import React, { Component } from 'react'  
  2.   
  3. export class ContactUs extends Component {  
  4.     render() {  
  5.         const { params } = this.props.match  
  6.         return (  
  7.             <div>  
  8.                 <p>{params.name}</p>  
  9.                 Contact Us Component  
  10.             </div>  
  11.         )  
  12.     }  
  13. }  
  14.   
  15. export default ContactUs  
The output will be as below,
 
 

Implementing Nested Routes in React

 
Nested routes are used to implement sub-routes like contactus/Priyanka, contactus/test. For implementing nested routes, we need to import react-router component,
App.js
  1. import React from 'react';  
  2. import { Route, Link, Switch, BrowserRouter as Router } from 'react-router-dom'  
  3. import './App.css';  
  4. import Home from './components/Home';  
  5. import ContactUs from './components/ContactUs';  
  6. import NotFound from './components/notfound';  
  7. function App() {  
  8.   return (  
  9.     <Router>  
  10.       <div>  
  11.         <nav className="navbar navbar-expand-lg navbar-light bg-light">  
  12.           <ul className="navbar-nav mr-auto">  
  13.             <li><Link to={'/'} className="nav-link"> Home </Link></li>  
  14.             <li><Link to={'/ContactUs'} className="nav-link">Contact Us</Link></li>  
  15.           </ul>  
  16.         </nav>  
  17.         <hr />  
  18.         <Switch>  
  19.           <Route exact path="/" component={Home} />  
  20.           <Route path="/contactus" component={ContactUs} />  
  21.           <Route component={NotFound} />  
  22.         </Switch>  
  23.       </div>  
  24.     </Router>  
  25.   );  
  26. }  
  27.   
  28. export default App;   
Now in ContactUs.js component, we need to implement sub route in this component only,
  1. import React, { Component } from 'react'  
  2. import { Route, Link } from 'react-router-dom';  
  3.   
  4. const Contact = ({ match }) => <p>{match.params.name}</p>  
  5.   
  6. export class ContactUs extends Component {  
  7.     render() {  
  8.         const { url } = this.props.match  
  9.         return (  
  10.             <div>  
  11.                 <p>Contact Us Component</p>  
  12.                 <strong>select contact name</strong>  
  13.                 <ul>  
  14.                     <li><Link to="/contactus/Priyanka">Priyanka</Link></li>  
  15.                     <li><Link to="/contactus/test">Test</Link></li>  
  16.                 </ul>  
  17.                 <Route path="/contactus/:name" component={Contact}></Route>  
  18.             </div>  
  19.         )  
  20.     }  
  21. }  
  22.   
  23. export default ContactUs   
The output will be displayed as below,
 
 
In the above example, we are not getting a clue which link is clicked. So for that React provides a NavLink concept,
 
NavLink is used to style the active routes so that the user can identify which page he is user is navigating to.
 
Import NavLink from react-route-dom
 
Now replace all Link by NavLink component,
  1. import React from 'react';  
  2. import { Route,NavLink, Switch, BrowserRouter as Router } from 'react-router-dom'  
  3. import './App.css';  
  4. import Home from './components/Home';  
  5. import Contact from './components/ContactUs';  
  6. import NotFound from './components/notfound';  
  7. function App() {  
  8.   return (  
  9.     <Router>  
  10.       <div>  
  11.         <nav className="navbar navbar-expand-lg navbar-light bg-light">  
  12.           <ul className="navbar-nav mr-auto">  
  13.             <li><NavLink exact to={'/'} activeClassName="active"  className="nav-link"> Home </NavLink></li>  
  14.             <li><NavLink to={'/contactus'} activeClassName="active"  className="nav-link">Contact Us</NavLink></li>  
  15.           </ul>  
  16.         </nav>  
  17.         <hr />  
  18.         <Switch>  
  19.           <Route exact path="/" component={Home} />  
  20.           <Route path="/contactus" component={Contact} />  
  21.           <Route component={NotFound} />  
  22.         </Switch>  
  23.       </div>  
  24.     </Router>  
  25.   );  
  26. }  
  27.   
  28. export default App;   
contactus.js
  1. import React, { Component } from 'react'  
  2. import { Route, NavLink } from 'react-router-dom';  
  3.   
  4. const Contact = ({ match }) => <p>{match.params.name}</p>  
  5.   
  6. export class ContactUs extends Component {  
  7.     render() {  
  8.         return (  
  9.             <div>  
  10.                 <p>Contact Us Component</p>  
  11.                 <strong>Select contact name</strong>  
  12.                 <ul>  
  13.                     <li><NavLink to="/contactus/Priyanka">Priyanka</NavLink></li>  
  14.                     <li><NavLink to="/contactus/test">Test</NavLink></li>  
  15.                 </ul>  
  16.                 <Route path="/contactus/:name" component={Contact}></Route>  
  17.             </div>  
  18.         )  
  19.     }  
  20. }  
  21.   
  22. export default ContactUs  
The output will be displayed as below,
 
 
 

Summary

 
In this article, we have learned about Routing in React, how to implement the nested route and how to implement active link navigation, and the concept of the Switch. You can download the source code attached along with this article.