UI Development

Getting Started with React Router

Introduction 

Routing is a process where you want your URL tcorrespond with the component rendering on a page. In order to perform navigation without getting required page refreshed all the time when rendered, routing comes into action. We do not need routing to other pages for small applications as it is manageable. But as it turns into a large application, we    need navigation to combine multiple pages to perform routing. Therefore, router is used to perform routing.

SPA & Routing

In the modern days, we find many frameworks which prefer routing for single page applications. SPA has many section of pages divided and each page content has its own separate url pathname and requests server a plenty of times for the page reload, we use routing where it will just check the pathname and give us the desirable content.

React Router

React Router is a standard routing library for react applications. It has simple API with powerful features such as lazy code loading and dynamic routing.

Setup

Installation & Configuration

1.We need to install react router in our React App. If we don’t have one, then create one by using npx .

$ npx create-react-app file-name 

2.Now, install react-router by giving this command in your terminal.

$ npm install react-router-dom 

We declare routes via various components in an application.

Components

There are different categories of components in routing. They are:

Router

Based on the way of structuring URL’s or the type of app we build, we choose the router.

Basically, we have multiple types of router bundled in React. They are:

a.HashRouter:

It uses # in URL and stores the location in the hash portion. It looks something like this:

http://example.com/#/page

b.BrowserRouter:

Most of the web apps use BrowserRouter. It uses HTML 5 history API for providing clean history or URL’s. It is also the best-looking URL’s .Server Configuration should be done properly in these type of routers unlike HashRouters .

c.MemoryRouter:

In these kinds of router, history of URL’s are stored in memory. No Read and write operations are allowed .It is mostly used in automated testing .

3.Choose which router to import and incorporate it in the app entry point. i.e, index.js

Here, we will use BrowserRouter.

In index.js:

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

4.Now, by declaring Router component in render function of index.js, we can declare routes in any of the app components directly.

In index.js:

render( 
         <BrowserRouter> 
             <App /> 
         </BrowserRouter>, 
         document.getElementById("root") 
        );

 

Route Matchers

This component is usually loaded to get the matched URL. ‘Route’ and ‘Switch’ are the route matchers which when rendered loads the correct URL.

(I)ROUTE:

Route component uses 2 props.They are:

a. path:

It is used to know the URL you are looking for.

b. component:

It loads when the correct path matches with the component given.

Now, let’s declare route component to start routing.

5.Import the Route component in App.js.

In App.js:

import {Route} from ‘react-router-dom’; 

Firstly, you give the path to the homepage where you give “/”(slash) as a path. For the other pages, you give some name in the URL.

In App.js:

    <Route path="/" component={Home}/> 
    <Route path="/course" component={Course}/> 
    <Route path="/about" component={About}/>

React Router allows multiple routes to match. Here, Home Page matches all other routes since all the other routes even contain slash in the path. Therefore, we add exact prop to homepage component.

In App.js:

<Route path=”/” exact component={Home}/> 

When we run App.js, we still can see page reloading. React Router allows us to avoid page reloading by navigating on the client with the use of Link component.

(II)SWITCH:

Switch component is rendered when it finds its exact path matching the URL it is searching for and ignores the other routes. So, the paths given should be more specific. If no route matches, it renders nothing. Route path=”/”> will always match the complete URL since every URL starts with  a  ”/” (slash).So this <Route> component is to be mentioned in the last of our  Switch. If it doesn’t match the given URL’s, it will render this ending route component.

6.Import the switch component from react-router-dom and it renders the other components inside the switch component.It matches all the URL’s present in switch component.

In App.js:

<Switch> 
<Route exact path="/" component={Home} /> 
<Route path="/about" component={About} /> 
<Route path="/contact" component={Contact} /> 
<Route path=”/” component={} /> 
</Switch>

Navigation

These type of components are used for navigation between different routes without page reloading. Instead of requesting index.html over and over again, it doesn’t reload the page every time. To prevent this  behaviour, these type of components come in action. Hence, they are also called as route changers.

It contains Link, NavLink and Redirect components.

a.LINK:

This component is used by anchors which is usually managed by React Routers. React Router provides abstractions over anchors called Link. Link component creates anchors and asks you to specify and path to link including parameters. Whenever a link component is used, it renders an anchor element in the HTML document.It basically performs the action of prevent.default function internally and prevents

the default action of repeated loading of the page and makes the ease of navigation smoother and quicker. We add “to” prop in the path to navigate to the required page.

b.NAVLINK:

NavLink is much similar to Link component. It just adds the active class on the current item which can be seen in the developer tools. We can use this component when we wanted to add some styles to the current item in list.

7.In any page containing lists, you can remove the anchor tags and add Link and NavLink component.

<ul className="right">
  <li><Link to="/">Home</Link></li>
  <li><NavLink to="/about">About</NavLink></li>
  <li><NavLink to="/contact">Contact</NavLink></li>
</ul>

c.REDIRECT:

When you wish to force navigation , you can use Redirect component. We give the required path in the to prop. It replaces the current location with a new location in history. The data about the new location is passed via state.

Every component has its locations stored in history by keeping track of it, history object has its own methods like history.push and history.replace. history.push is called when Link component is rendered whereas Redirect component is rendered when history.replace.

DEMO:

In App.js:

import React, { Component } from 'react';
import { Link, Route, Switch } from 'react-router-dom';
import About from './About';
import Contact from './Contact';
import Home from './Home';
 
class App extends Component {
  render() {
    return (
      <div>
        <nav className="navbar navbar-light">
          <ul className="nav navbar-nav">
            <li><Link to="/">Home</Link></li>
            <li><Link to="/about">About</Link></li>
            <li><Link to="/contact">Contact</Link></li>
          </ul>
       </nav>
 
    <Switch>
      <Route exact path="/" component={Home}/>
      <Route path="/about" component={About}/>
       <Route path="/contact" component={Contact}/>
    </Switch>
 
    </div>
    );
  }
}
export default App;

In index.js:

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

 

In Home.js:
const Home = () => (
  <div>
    <h2>Home</h2>
  </div>
)
In About.js:
const About = () => (
  <div>
    <h2>About</h2>
  </div>
)

In Contact.js

const Contact = () => (
  <div>
    <h2>Contact</h2>
  </div>
)

8.Now run npm start in your terminal to see the output in action following routing using various route components.

About The Author