×
☰ See All Chapters

How To Handle Routing in React Apps - React Router

Imagine we are navigating from one page to another page (One view to another view). Where in both the pages header, footer, and template remains same. To display a new view, an application need to send a new URL to the server and downloaded the entire page. To overcome this we can use AJAX and XMLHttpRequests and we can achieve Single Page Applications (SPAs).

Single Page Applications is an application which has only one page (for example only one html file) for entire application. All other view and different screens of the applications are obtained just by adding/updating/deleting the components from same page. Today, single-page applications (SPAs) have taken center stage. The browser communicates asynchronously with the server, so it can send and receive data without having to process HTTP requests and responses. This saves time and provides the user with a fluid, dynamic experience.

When we use AJAX to achieve SPA, for all the screens we need to have same URL. When I click on a button with AJAX request, it will update the DOM but URL will remain same. Only some part of the screen will get update. Now if we want different URL for different view with SPA, AJAX cannot be used. There are advantages to having multiple URLs. Users can visit specific parts of a page and they can move between these parts using the browser's Back/Forward buttons.

The goal of React routing is to enable SPAs to associate different URLs with different components and states. Another major advantage of React routing is that it enables lazy loading of application code. This means that the client will only download the code it needs instead of having to download all of the code at once.

React Router is the de-facto React routing library, and it's one of the most popular projects built on top of React. React at its core is a very simple library, and it does not dictate anything about routing.

Installing React Router

To add React Router in your application, run this in the terminal from the root directory of the application:

With Yarn:

yarn add react-router-dom

With npm:

npm install react-router-dom

routing-in-react-apps-0
 

If react router is already installed and if you would like to upgrade the version then you can use @latest flag:

npm install react-router-dom@latest

Types of routes

React Router provides two different kinds of routes:

  • BrowserRouter 

  • HashRouter 

 

One builds classic URLs, the other builds URLs with the hash:

BrowserRouter: https://application.com/dashboard /* BrowserRouter */

HashRouter: https://application.com/#/dashboard /* HashRouter */

Which one to use is mainly dictated by the browsers you need to support. BrowserRouter uses the History API, which is relatively recent, and not supported in IE9 and below. If you don't have to worry about older browsers, it's the recommended choice.

Elements of routing

The 3 components you will interact the most when working with React Router are:

  1. BrowserRouter, usually aliased as Router 

  2. Link 

  3. Route 

BrowserRouter

BrowserRouter wraps all your Route components. It is imported from react-router-dom

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

function DemoComponent() {

        return (

                <Router>

                        … …

                </Router>

        );

}

export default DemoComponent;

Link

The Link component is used to trigger new routes. You import it from react-router-dom, and you can add the Link components to point at different routes, with the to attribute:

import { BrowserRouter as Router, Link, Route, Routes, Outlet } from 'react-router-dom';

 

function DemoComponent() {

        return (

                <Router>

                        <div>

                                <nav>

                                        <Link to={`/`}>Dashboard</Link>

                                        <Link to={`/employee`}>Employee</Link>

                                        <Link to={`/student`}>Student</Link>

                                </nav>

                        </div>

                        <Outlet />

                </Router>

        );

}

export default DemoComponent;

 

 

Route

Route components are responsible for showing - or hiding - the components they contain. All Route elements should be wrapped inside Routes component. Now let's add the Route component in the above snippet to make things actually work as we want:

import { BrowserRouter as Router, Link, Route, Routes, Outlet } from 'react-router-dom';

import DashboardComponent from "./dashboard.component";

import EmployeeComponent from "./employee.component";

import StudentComponent from "./student.component";

 

function DemoComponent() {

        return (

                <Router>

                        <div>

                                <nav>

                                        <Link to={`/`}>Dashboard</Link>

                                        <Link to={`/employee`}>Employee</Link>

                                        <Link to={`/student`}>Student</Link>

                                </nav>

                                <Routes>

                                        <Route exact path="/" element={<DashboardComponent />} />

                                        <Route path="/employee" element={<EmployeeComponent />} />

                                        <Route path="/student" element={<StudentComponent />} />

                                </Routes>

                        </div>

                        <Outlet />

                </Router>

        );

}

export default DemoComponent;

 

Routing example in function components

dashboard.component.js

function DashboardComponent() {

        return <h1>Dashboard Component</h1>;

}

export default DashboardComponent;

employee.component.js

function EmployeeComponent() {

        return <h1>Employee Component</h1>;

}

export default EmployeeComponent;

student.component.js

function StudentComponent() {

        return <h1>Student Component</h1>;

}

export default StudentComponent;

demo.component.js

import { BrowserRouter as Router, Link, Route, Routes, Outlet } from 'react-router-dom';

import DashboardComponent from "./dashboard.component";

import EmployeeComponent from "./employee.component";

import StudentComponent from "./student.component";

 

function DemoComponent() {

        return (

                <Router>

                        <div>

                                <nav>

                                        <Link to={`/`}>Dashboard</Link><br></br>

                                        <Link to={`/employee`}>Employee</Link><br></br>

                                        <Link to={`/student`}>Student</Link><br></br>

                                </nav>

                                <Routes>

                                        <Route exact path="/" element={<DashboardComponent />} />

                                        <Route path="/employee" element={<EmployeeComponent />} />

                                        <Route path="/student" element={<StudentComponent />} />

                                </Routes>

                        </div>

                        <Outlet />

                </Router>

        );

}

export default DemoComponent;

index.js

import React from 'react';

import ReactDOM from 'react-dom';

import './index.css';

import DemoComponent from './components/demo.component';

import reportWebVitals from './reportWebVitals';

 

ReactDOM.render(

        <React.StrictMode>

                <DemoComponent></DemoComponent>

        </React.StrictMode>,

        document.getElementById('root')

);

 

reportWebVitals();

routing-in-react-apps-1
 
routing-in-react-apps-2
 

When the route matches / , the application shows the Dashboard component. When the route is changed by clicking the "Employee" link to /employee , the Dashboard component is removed and the EMployee component is inserted in the DOM. Notice the exact attribute. Without this exact attribute, path="/" would also match /employee and /student , since / is contained in the route.

Routing example in class components

dashboard.component.js

import React from 'react';

 

class DashboardComponent extends React.Component {

        render() {

                return <h1>Dashboard Component</h1>;

        }

 

}

export default DashboardComponent;

employee.component.js

import React from 'react';

 

class EmployeeComponent extends React.Component {

        render() {

                return <h1>Employee Component</h1>;

        }

 

}

export default EmployeeComponent;

student.component.js

import React from 'react';

 

class StudentComponent extends React.Component {

        render() {

                return <h1>Student Component</h1>;

        }

 

}

export default StudentComponent;

demo.component.js

 

import React from 'react';

import { BrowserRouter as Router, Link, Route, Routes, Outlet } from 'react-router-dom';

import DashboardComponent from "./dashboard.component";

import EmployeeComponent from "./employee.component";

import StudentComponent from "./student.component";

 

class DemoComponent extends React.Component {

   render() {

      return (

         <Router>

                        <div>

                                <nav>

                                        <Link to={`/`}>Dashboard</Link><br></br>

                                        <Link to={`/employee`}>Employee</Link><br></br>

                                        <Link to={`/student`}>Student</Link><br></br>

                                </nav>

                                <Routes>

                                        <Route exact path="/" element={<DashboardComponent />} />

                                        <Route path="/employee" element={<EmployeeComponent />} />

                                        <Route path="/student" element={<StudentComponent />} />

                                </Routes>

                        </div>

                        <Outlet />

                </Router>

      )

   }

}

export default DemoComponent;

index.js

import React from 'react';

import ReactDOM from 'react-dom';

import './index.css';

import DemoComponent from './components/demo.component';

import reportWebVitals from './reportWebVitals';

 

ReactDOM.render(

        <React.StrictMode>

                <DemoComponent></DemoComponent>

        </React.StrictMode>,

        document.getElementById('root')

);

 

reportWebVitals();

 
 

All Chapters
Author