Routing In ReactJS

Introduction

 
In this article we will learn routing in Reactjs from the  beginning. Routing is a mechanism to redirect the users from one page to another page, and provides the navigation from one page to another page.
 
Prerequisites
  • We should have a basic knowledge of ReactJS
  • Visual Studio Code should be installed
  • Node and NPM installed

React router

 
React router is a routing library built on top of the react which is used to create the routing in React apps.
 
Create React.js Project 
  1. npx create-react-app routingdemo  
 Install react router
 
Install React router by using the  following command.
  1. npm install react-router-dom --save   
Install bootstrap in this project by using the following command.
  1. npm install --save bootstrap      
Now, open the index.js file and add Bootstrap reference.
  1. import 'bootstrap/dist/css/bootstrap.min.css';  
Project structure
 
 
I have created two folders, layout and Views. Inside these folders I  have created  the following components. 
 
Layout Folder components
  • Footer.js
  • Header.js
  • Leftside.js
  • Layout.js
Views folder conponents
  • Addemployee.js
  • Dashboard.js
  • Editemployee.js
  • Employee.js
  • Profile.js
  • Setting.js
Now let's create one more file named 'route.js', in this file we defined routing. Open route.js file and add the  following code
  1. import  React from 'react';  
  2. const Dashboard=React.lazy(()=>import('./Views/Dashboard'));  
  3. const setting=React.lazy(()=>import('./Views/Setting'))  
  4. const employee=React.lazy(()=>import('./Views/Employee'))  
  5. const addemployee=React.lazy(()=>import('./Views/Addemployee'))  
  6. const editemployee=React.lazy(()=>import('./Views/Editemployee'))  
  7. const profile=React.lazy(()=>import('./Views/Profile')) 
  8. const notfound=React.lazy(()=>import('./PageNotFound'))
  9. const routes = [  
  10.     { path: '/Dashboard', component: Dashboard },  
  11.     { path: '/setting', component: setting },  
  12.     { path: '/employee',  component: employee },  
  13.     { path: '/addemployee',  component: addemployee },  
  14.     { path: '/profile',  component: profile },  
  15.     { path: '/editemployee/:id', exact: true,  component: editemployee }, 
  16.     { component:notfound }
  17. ];  
  18.   
  19. export default routes;  
Now go to Layout folder and open header.js file and  add the following code.
  1. import React, { Component } from 'react'  
  2. import { Link } from 'react-router-dom'  
  3.   
  4. export class Header extends Component {  
  5.   render() {  
  6.     return (  
  7.       <div>  
  8.         <nav class="navbar navbar-expand navbar-light bg-white topbar mb-4 static-top shadow">  
  9.           <ul class="navbar-nav ml-auto">  
  10.   
  11.             <li class="nav-item dropdown no-arrow d-sm-none">  
  12.             </li>  
  13.             <li class="nav-item dropdown no-arrow mx-1">  
  14.             </li>  
  15.             <div class="topbar-divider d-none d-sm-block"></div>  
  16.             <li class="nav-item dropdown no-arrow">  
  17.               <a class="nav-link dropdown-toggle" href="#" id="userDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">  
  18.                 <span class="mr-2 d-none d-lg-inline text-gray-600 small">Sanwar</span>  
  19.                 <img src="https://img.icons8.com/officel/16/000000/user.png" />  
  20.               </a>  
  21.               <div class="dropdown-menu dropdown-menu-right shadow animated--grow-in" aria-labelledby="userDropdown">  
  22.                 <Link class="dropdown-item" to="/profile">  
  23.                   <i class="fas fa-user fa-sm fa-fw mr-2 text-gray-400"></i>  
  24.         Profile  
  25.       </Link>  
  26.                 <div class="dropdown-divider"></div>  
  27.                 <a class="dropdown-item" href="#" data-toggle="modal" data-target="#logoutModal">  
  28.                   <i class="fas fa-sign-out-alt fa-sm fa-fw mr-2 text-gray-400"></i>  
  29.         Logout  
  30.       </a>  
  31.               </div>  
  32.             </li>  
  33.           </ul>  
  34.         </nav>  
  35.       </div>  
  36.     )  
  37.   }  
  38. }  
  39.   
  40. export default Header  
Now open Footer.js component and add the following code.
  1. import React, { Component } from 'react'  
  2. export class Footer extends Component {  
  3.     render() {  
  4.         return (  
  5.             <div>  
  6.                  <footer class="sticky-footer bg-white">  
  7.              <div class="container my-auto">  
  8.               <div class="copyright text-center my-auto">  
  9.             <span>Rotuing in ReactJS</span>  
  10.           </div>  
  11.         </div>  
  12.       </footer>  
  13.             </div>  
  14.         )  
  15.     }  
  16. }  
  17. export default Footer  
  Now open Leftside.js component and  add the following code.
  1. import React, { Component } from 'react'  
  2. import { Link } from 'react-router-dom';  
  3. export class Leftside extends Component {  
  4.     render() {  
  5.         return (  
  6.             <div>  
  7.                 <ul class="navbar-nav bg-gradient-primary sidebar sidebar-dark accordion" id="accordionSidebar">  
  8.                     <a class="sidebar-brand d-flex align-items-center justify-content-center" href="index.html">  
  9.                         <div class="sidebar-brand-text mx-3">React Routing </div>  
  10.                     </a>  
  11.                     <hr class="sidebar-divider my-0" />  
  12.                     <hr class="sidebar-divider" />  
  13.                      <li class="nav-item">  
  14.                         <Link class="nav-link" to="/Dashboard"> <i class="fas fa-fw fa-home"></i>Home</Link>  
  15.                     </li>  
  16.                     <li class="nav-item">  
  17.                         <Link class="nav-link" to="/employee"> <i class="fas fa-fw fa-user"></i>Employee</Link>  
  18.                     </li>  
  19.                     <li class="nav-item">  
  20.                         <Link class="nav-link" to="/setting">  <i class="fas fa-fw fa-cog"></i>Setting</Link>  
  21.                     </li>  
  22.                 </ul>  
  23.             </div>  
  24.         )  
  25.     }  
  26. }  
  27.   
  28. export default Leftside  
Now open Layout.js component and import header, footer and leftside components reference. In this component, add the following code.
  1. import React, { Component, Suspense } from 'react';  
  2. import Leftside from './Leftside';  
  3. import Header from './Header'  
  4. import Footer from './Footer'  
  5. import routes from '../routes';  
  6. import * as router from 'react-router-dom';  
  7. import {  
  8.     Route, Switch, Redirect  
  9. } from 'react-router-dom';  
  10. export class Layout extends Component {  
  11.     loading = () => <div className="animated fadeIn pt-1 text-center">Loading...</div>  
  12.     render() {  
  13.         return (  
  14.             <div>  
  15.                 <div id="wrapper">  
  16.                     <Leftside></Leftside>  
  17.                     <div id="content-wrapper" class="d-flex flex-column">  
  18.                         <div id="content">  
  19.                             <Header />  
  20.                              <Suspense fallback={this.loading()}>  
  21.                             <Switch>  
  22.                                 {routes.map((route, idx) => {  
  23.                                     return route.component ? (  
  24.                                         <Route  
  25.                                             key={idx}  
  26.                                             path={route.path}  
  27.                                             exact={route.exact}  
  28.                                             name={route.name}  
  29.                                             render={props => (  
  30.                                                 <route.component {...props} />  
  31.                                             )} />  
  32.                                     ) : (null);  
  33.                                 })}  
  34.                                 <Redirect from="/" to="/dashboard" />  
  35.                             </Switch>  
  36.                             </Suspense>  
  37.                         </div>  
  38.                         <Footer />  
  39.                     </div>  
  40.                 </div>  
  41.             </div>  
  42.         )  
  43.     }  
  44. }  
  45.   
  46. export default Layout  
Layout structure
 
 
Now go to Views folder and open Dashboard.js component and add the  following code.
  1. import React, { Component } from 'react'  
  2.   
  3. export class Dashboard extends Component {  
  4.     render() {  
  5.         return (  
  6.             <div>  
  7.                 <h1>Welcome to React Routing Dashboard</h1>  
  8.             </div>  
  9.         )  
  10.     }  
  11. }  
  12.   
  13. export default Dashboard  
Now open Addemployee.js component and following code. 
  1. import React, { Component } from 'react'  
  2.   
  3. export class Addemployee extends Component {  
  4.     render() {  
  5.         return (  
  6.             <div>  
  7.   
  8.   
  9.   
  10.                 <div class="row">  
  11.                     <div class="col-lg-2"></div>  
  12.                     <div class="col-lg-8">  
  13.                         <div  style={{"padding":"0rem!important"}}>  
  14.                             <div class="text-center">  
  15.                                 <h1 class="h4 text-gray-900 mb-4">Create new Employee!</h1>  
  16.                             </div>  
  17.                             <form >  
  18.                                 <div class="form-group row">  
  19.                                     <div class="col-sm-12 mb-3 mb-sm-0">  
  20.                                         <input type="text" class="form-control form-control-user" id="eEmployeetName" placeholder="Employee Name" />  
  21.                                     </div>  
  22.   
  23.                                 </div>  
  24.                                 <div class="form-group row">  
  25.   
  26.                                     <div class="col-sm-12">  
  27.                                         <input type="text" class="form-control form-control-user" id="City" placeholder="City" />  
  28.                                     </div>  
  29.                                 </div>  
  30.                                 <div class="form-group">  
  31.                                     <input type="email" class="form-control form-control-user" id="Email" placeholder="Email Address" />  
  32.                                 </div>  
  33.                                 <div class="form-group">  
  34.                                     <input type="email" class="form-control form-control-user" id="Department" placeholder="Department" />  
  35.                                 </div>  
  36.   
  37.                                 <a href="login.html" class="btn btn-primary btn-user btn-block">  
  38.                                     Add  Employee  
  39.                           </a>  
  40.   
  41.   
  42.                             </form>  
  43.   
  44.                         </div>  
  45.                     </div>  
  46.                 </div>  
  47.   
  48.             </div>  
  49.         )  
  50.     }  
  51. }  
  52.   
  53. export default Addemployee  
Now open Setting.js component and add the following code.
  1. import React, { Component } from 'react'  
  2.   
  3. export class Setting extends Component {  
  4.     render() {  
  5.         return (  
  6.             <div>  
  7.                <h1>Welcome to React Routing Setting Dashboard</h1>  
  8.             </div>  
  9.         )  
  10.     }  
  11. }  
  12.   
  13. export default Setting  
Now open Profile.js component and add the following code. 
  1. import React, { Component } from 'react'  
  2.   
  3. export class Profile extends Component {  
  4.     render() {  
  5.         return (  
  6.             <div>  
  7.                 <h3>Profile</h3>  
  8.             </div>  
  9.         )  
  10.     }  
  11. }  
  12.   
  13. export default Profile  
Now open Employee.js component and add the following code.
  1. import React, { Component } from 'react'  
  2. import { Link } from 'react-router-dom';  
  3. export class Color extends Component {  
  4.       
  5.     render() {  
  6.         const employee = `/editemployee/${1}`  
  7.         return (  
  8.             <div>  
  9.                 <div class='container-fluid' >        
  10.            <div className="row title" style={{marginBottom: "20px"}} >        
  11.            <div class="col-sm-12 ">     
  12.            <div class="col-sm-9 btn">  
  13.                </div>  
  14.                <div class="col-sm-3 btn btn-info nav-item">  
  15.                <Link style={{"color":"white"}} class="nav-link" to="/addemployee"> <i style={{"color":"white"}} class="fas fa-fw fa-user"></i>Add Employee</Link>  
  16.                </div>  
  17.             
  18.            </div>        
  19.            </div>    
  20.        </div>    
  21.                 <table class="table">  
  22.                     <thead>  
  23.                         <tr>  
  24.                             <th>Employee name</th>  
  25.                             <th>City</th>  
  26.                             <th>Email</th>  
  27.                             <th>Department</th>  
  28.                             <th></th>  
  29.                         </tr>  
  30.                     </thead>  
  31.                     <tbody>  
  32.                         <tr>  
  33.                             <td>John</td>  
  34.                             <td>Doe</td>  
  35.                             <td>[email protected]</td>  
  36.                             <td>IT</td>  
  37.                             <td>  
  38.                              
  39.                             <Link class="btn btn-info" to={employee}>Edit</Link>  
  40.                                   
  41.                                      
  42.                             </td>  
  43.   
  44.                         </tr>  
  45.                         <tr>  
  46.                             <td>Mary</td>  
  47.                             <td>Moe</td>  
  48.                             <td>[email protected]</td>  
  49.                             <td>HR</td>  
  50.                             <td>  
  51.                                 <button type="button" class="btn btn-info">Edit</button>  
  52.                                   
  53.                             </td>  
  54.                         </tr>  
  55.                         <tr>  
  56.                             <td>July</td>  
  57.                             <td>Dooley</td>  
  58.                             <td>[email protected]</td>  
  59.                             <td>IT</td>  
  60.                             <td>  
  61.                               <button type="button" class="btn btn-info">Edit</button>  
  62.                                      
  63.                             </td>  
  64.                         </tr>  
  65.                     </tbody>  
  66.                 </table>  
  67.             </div>  
  68.         )  
  69.     }  
  70. }  
  71.   
  72. export default Color  
Now open Editemployee.js component and add the following code.
  1. import React, { Component } from 'react'  
  2.   
  3. export class Editemployee extends Component {  
  4.     render() {  
  5.         return (  
  6.             <div>  
  7.                  <div class="row">  
  8.                     <div class="col-lg-2"></div>  
  9.                     <div class="col-lg-8">  
  10.                         <div  style={{"padding":"0rem!important"}}>  
  11.                             <div class="text-center">  
  12.                                 <h1 class="h4 text-gray-900 mb-4">Update Employee</h1>  
  13.                             </div>  
  14.                             <form >  
  15.                                 <div class="form-group row">  
  16.                                     <div class="col-sm-12 mb-3 mb-sm-0">  
  17.                                         <input type="text" class="form-control form-control-user" id="eEmployeetName" placeholder="Employee Name" />  
  18.                                     </div>  
  19.   
  20.                                 </div>  
  21.                                 <div class="form-group row">  
  22.   
  23.                                     <div class="col-sm-12">  
  24.                                         <input type="text" class="form-control form-control-user" id="City" placeholder="City" />  
  25.                                     </div>  
  26.                                 </div>  
  27.                                 <div class="form-group">  
  28.                                     <input type="email" class="form-control form-control-user" id="Email" placeholder="Email Address" />  
  29.                                 </div>  
  30.                                 <div class="form-group">  
  31.                                     <input type="email" class="form-control form-control-user" id="Department" placeholder="Department" />  
  32.                                 </div>  
  33.   
  34.                                 <a href="login.html" class="btn btn-primary btn-user btn-block">  
  35.                                 Update  Employee  
  36.                           </a>  
  37.   
  38.   
  39.                             </form>  
  40.   
  41.                         </div>  
  42.                     </div>  
  43.                 </div>  
  44.             </div>  
  45.         )  
  46.     }  
  47. }  
  48.   
  49. export default Editemployee  
Now open index.js file and add the following code
  1. import React from 'react';  
  2. import ReactDOM from 'react-dom';  
  3. import './index.css';  
  4. import App from './App';  
  5. import * as serviceWorker from './serviceWorker';  
  6. import { BrowserRouter } from 'react-router-dom';  
  7. ReactDOM.render(  
  8.   <BrowserRouter>  
  9.   <App />  
  10. </BrowserRouter>  
  11. , document.getElementById('root')  
  12. );  
  13. serviceWorker.unregister();  
Open app.js file and add the following code
  1. import React from 'react';  
  2. import logo from './logo.svg';  
  3. import './App.css';  
  4. import Layout from './Layout/Layout'  
  5. function App() {  
  6.   return (  
  7.     <div className="App">  
  8.       <Layout></Layout>  
  9.     </div>  
  10.   );  
  11. }  
  12.   
  13. export default App; 
Now run the project by using 'Npm start'.
 
 
 Click on Employee
 
 
Click on Addemployee Button 
 
 
Click on Edit button 
 
To check if page is not found component, enter any invaild text in url 
 
 

Summary


In this article, we learned about routing in ReactJS applications.