×

React Router

What is React Router?

Routing is a process by which a user can direct to different pages based on their actions and requests. ReactJS router is generally used to develop single web page applications. React Router is used for defining multiple routes in an application. When a user enters any specific URL into the browser, and if the path of that URL matches with any ‘router’ inside the router file, then the user will be redirected towards a particular route.

React router is used to establish routing in the react application by using the React router package. It gives a synchronous URL to the browser with data that will be displayed on the webpage. It maintains the behavior and standard structure of the application and mainly used for creating single page web applications.

Why React Router?

React Router is also used for displaying the multiple views in a single page web application. Without using the React Router, you cannot display the multiple views in the React applications. The social media websites like Facebook, Instagram, etc. use React router for rendering multiple views.

Components of React Router

There are mainly two types of router components:

  • <BrowserRouter>: It is used to handle the dynamic URL.
  • <HashRouter>: It is used to handle the static request.

Benefits of React Router

React Router has several benefits that are given as follows:

  • In React Router, it is not mandatory to manually set the browser history.
  • Links are used for navigating the internal links of the application, similarly as an anchor tag.
  • There is a use of switch feature for rendering.
  • The router requires only a single child element.

Step by Step procedure for installing React Router

There are three packages to react for routing. These are as follows:

  • react-router: It gives the core routing functions and components for the react-router applications.
  • react-router-native: It is for mobile apps.
  • react-router-dom: It is used for designing web applications.

Step1:  Install a React Router

A simple way to directly install the react-router in your application is as follows. You have to run the following command in your command prompt:

npm install react-router

Install a React Router

Step 2: Now, we have to create two more components About.js and Contact.js along with App.js (already present).

About.js

import React from 'react';

class About extends React.Component {
  render() {
    return (
      <div>
        About
      </div>
    );
  }
}

export default About;

Contact.js

import React from 'react';

class About extends React.Component {
  render() {
    return (
      <div>
        contact
      </div>
    );
  }
}

export default About;

App.js

import React from 'react';

class About extends React.Component {
  render() {
    return (
      <div>
        Home
      </div>
    );
  }
}

export default About;

Step 3: To perform routing, you need to open the index.js file and import all the three component files in it. You have to import line: import { Route, Link, BrowserRouter as Router } from 'react-router-dom', which helps in the implementation of routing.

Index.js

import React from 'react';
import ReactDOM from 'react-dom';
import { Route, Link, BrowserRouter as Router } from 'react-router-dom';
import './index.css';
import App from './App';
import About from './About';
import Contact from './Contact';

const routing = (
  <Router>
    <div>
      <h2>React Router Example</h2>
      <nav>
        <ul>
          <li>
            <Link to="/">Home</Link>
          </li>
          <li>
            <Link to="/about">About</Link>
          </li>
          <li>
            <Link to="/contact">Contact</Link>
          </li>
        </ul>
      </nav>
      <Route exact path="/" component={App} />
      <Route path="/about" component={About} />
      <Route path="/contact" component={Contact} />
    </div>
  </Router>
);

ReactDOM.render(routing, document.getElementById('root'));

Now open your command prompt and start the npm by using the npm start command. After the successful compilation, you will get the following output:

Now open your command prompt

If you write localhost:3000/about manually in the browser, then the About component is rendered on the screen, and you will get the following output:

About component is rendered on the screen

In the above output, you can notice that the home component is still rendered. It happens because the path attribute of the home path is ‘/’ and the path attribute of about path is ‘/about’, and it can be observed that slash (/) is common in both of the paths and renders both components.

If you want to stop this behavior, you have to use exact prop. It can be clear from the following example:

Index.js

import React from 'react';
import ReactDOM from 'react-dom';
import { Route, Link, BrowserRouter as Router } from 'react-router-dom';
import './index.css';
import App from './App';
import About from './About';
import Contact from './Contact';

const routing = (
  <Router>
    <div>
      <nav>
        <ul>
          <li>
            <Link to="/">Home</Link>
          </li>
          <li>
            <Link to="/about">About</Link>
          </li>
          <li>
            <Link to="/contact">Contact</Link>
          </li>
        </ul>
      </nav>
      <Route exact path="/" component={App} />
      <Route path="/about" component={About} />
      <Route path="/contact" component={Contact} />
    </div>
  </Router>
);

ReactDOM.render(routing, document.getElementById('root'));

Output:

Example of React Router

Adding Navigation using Link Component

Sometimes, we require multiple links on a single page. If we click on any of the specific links, it should load the page, which is associated with that link without any reloading of the webpage. To perform this, we have to import <Link> component in the index.js file.

What is Link Component?

It is the component that is used for creating the links that allow you to navigate on different URLs and render its content without the reloading of the webpage.

Example

Index.js

import React from 'react';
import ReactDOM from 'react-dom';
import { Route, Link, BrowserRouter as Router } from 'react-router-dom';
import './index.css';
import App from './App';
import About from './About';
import Contact from './Contact';

const routing = (
  <Router>
    <div>
      <h2>React Router Example (Navigation with Link Component)</h2>
      <nav>
        <ul>
          <li><Link to="/">Home</Link></li>
          <li><Link to="/about">About</Link></li>
          <li><Link to="/contact">Contact</Link></li>
        </ul>
      </nav>
      <Route exact path="/" component={App} />
      <Route path="/about" component={About} />
      <Route path="/contact" component={Contact} />
    </div>
  </Router>
);

ReactDOM.render(routing, document.getElementById('root'));

Output:

What is Link Component

When you click on About and Contact link, you will see that the URL is changing, and the component of that specific link is rendered on the screen.

When you click on the About link, you will get the following output:

When you click on the About link,

When you click on the Contact link, you will get the following output:

you click on the Contact link

We can also add some styles to the link, such that if we click on any specific link, it should be easily identified which link is active. For performing it, the React router gives NavLink instead of Link. The NavLink has the activeStyle property, which means when we click on the Link, it provides a specific style by which it can be easily identified which one is currently active.

It can be clear with the following example:

Example:

import React from 'react';
import ReactDOM from 'react-dom';
import { BrowserRouter as Router, Route, Link } from 'react-router-dom';
import './index.css';
import App from './App';
import About from './About';
import Contact from './Contact';

const route = (
  <Router>
    <div>
      <h2>React Router Example</h2>
      <nav>
        <ul>
          <li>
            <Link to="/">Home</Link>
          </li>
          <li>
            <Link to="/about">About</Link>
          </li>
          <li>
            <Link to="/contact">Contact</Link>
          </li>
        </ul>
      </nav>
      <Route exact path="/" component={App} />
      <Route path="/about" component={About} />
      <Route path="/contact" component={Contact} />
    </div>
  </Router>
);

ReactDOM.render(route, document.getElementById('root'));

Output:

You will get the following output after the successful compilation of the above code.

get the following output after the successful compilation

Because the Home link is currently active so, the color of the Home link is red. When you click on the About link, the color of the link turns into red, because the link gets active.

the color of the Home link is red

Similarly, when you click on the Contact link, the link gets active, and the color turns to red.

when you click on the Contact link

Note: The Link component allows you to navigate the different routes on the website, whereas the NavLink component is used for adding the styles to the active routes.

React Router Switch

The <Switch> is used for rendering the components only when the URL is matched. Otherwise, it returns the notfound component.

Let us try to create the notfound component.

Notfound.js

import React from 'react';

const NotFound = () => {
  return <div>Not found</div>;
};

export default NotFound;

Index.js

import React from 'react';
import ReactDOM from 'react-dom';
import { BrowserRouter as Router, Route, Link, NavLink, Switch } from 'react-router-dom';
import './index.css';
import App from './App';
import About from './About';
import Contact from './Contact';
import Notfound from './Notfound';

const route = (
  <Router>
    <div>
      <h2>React Router Example</h2>
      <nav>
        <ul>
          <li><NavLink exact to="/">Home</NavLink></li>
          <li><NavLink to="/about">About</NavLink></li>
          <li><NavLink to="/contact">Contact</NavLink></li>
        </ul>
      </nav>
      <Switch>
        <Route exact path="/" component={App} />
        <Route path="/about" component={About} />
        <Route path="/contact" component={Contact} />
        <Route component={Notfound} />
      </Switch>
    </div>
  </Router>
);

ReactDOM.render(route, document.getElementById('root'));

Output:

If you manually enter the wrong URL, then it will give you the Not Found error. It will get clear in the following image:

you the Not Found error

React Router <Redirect>

A <Redirect> component is used for redirecting to another route in our application to maintain the old URLs. You can place it anywhere in the route hierarchy.

Nested Routing in React

It allows you to render the sub-routes in your application. The following example will help you to understand it.

Example:

Index.js

import React from 'react';
import ReactDOM from 'react-dom';
import { BrowserRouter as Router, Route, Link, NavLink, Switch } from 'react-router-dom';
import './index.css';
import App from './App';
import About from './About';
import Contact from './Contact';
import Notfound from './Notfound';

const route = (
  <Router>
    <div>
      <h2>React Router Example</h2>
      <nav>
        <ul>
          <li>
            <NavLink exact to="/" activeClassName="active">
              Home
            </NavLink>
          </li>
          <li>
            <NavLink to="/about" activeClassName="active">
              About
            </NavLink>
          </li>
          <li>
            <NavLink to="/contact" activeClassName="active">
              Contact
            </NavLink>
          </li>
        </ul>
      </nav>

      <Switch>
        <Route exact path="/" component={App} />
        <Route path="/about" component={About} />
        <Route path="/contact" component={Contact} />
        <Route component={Notfound} />
      </Switch>
    </div>
  </Router>
);

ReactDOM.render(route, document.getElementById('root'));

In the Contact.js file, we require to import the React Router component to implement the subroutes.

Contact.js

import React from 'react';
import { Route, Link } from 'react-router-dom';

const Contacts = ({ match }) => {
  return <div>{match.params.id}</div>;
};

class Contact extends React.Component {
  render() {
    const { url } = this.props.match;

    return (
      <div>
        <h2>This is Contact Page</h2>
        <p>Select contact Id</p>
        <ul>
          <li>
            <Link to={`${url}/1`}>Contact 1</Link>
          </li>
          <li>
            <Link to={`${url}/2`}>Contact 2</Link>
          </li>
          <li>
            <Link to={`${url}/3`}>Contact 3</Link>
          </li>
        </ul>
        <Route path={`${url}/:id`} component={Contacts} />
      </div>
    );
  }
}

export default Contact;

Output:

Once the code gets successfully compiled, you will get the following output:

code gets successfully compiled

After clicking the Contact, you will get the contact list, and on clicking any contact from the contact list you will also get the corresponding output:

on clicking any contact from the contact list

Related Topics

React Environment Setup Step by Step

React Environment Setup This section will provide you the information about how to set up an environment for the successful development of ReactJS application: Pre-Requisite for ReactJS NodeJS and NPMReact and React DOMWebpackBabel There are two...

5 minutes read.

React Code Splitting

React Code Splitting React Code Splitting is the procedure of splitting the bundle files by which the files get easily loaded on the webpage. The react application bundles the files by using...

4 minutes read.

React Forms

React Forms Forms are the important part of any web application. It allows the interaction of the user with the app as well as the gathering of the information from the...

3 minutes read.

React Props Validation

React Props Validation As we know, props are a suitable mechanism for passing the read-only attributes to react components. The props are required to be correctly used in the component. If it is...

5 minutes read.

React Bootstrap

React Bootstrap React has a widely used JavaScript framework for creating web applications, and Bootstrap has become the most popular CSS framework. Single-page apps have become popular from the last few...

9 minutes read.

React Components

React Components Former, the developers used to write more than thousands of lines of code to develop a single-page application. These applications follow the structure of traditional DOM, and it was very challenging to make...

2 minutes read.

React Flux

React Flux Introduction It is an application architecture that is internally used by Facebook to build the client-web application with react. It is useful when the project includes dynamic data, and...

2 minutes read.

React State

React State The state is an updatable structure which is used for containing data or information about the component. The state in a component can be changed over time. The change...

3 minutes read.

React Animation

React Animation The animation is a procedure in which an image is manipulated to appear as a moving image. It is widely used to create an interactive web application. In React, we have to...

4 minutes read.

React Router

What is React Router? Routing is a process by which a user can direct to different pages based on their actions and requests. ReactJS router is generally used to develop single...

10 minutes read.

React Keys

React Keys A key can be defined as a unique identifier. In React, it is used for identifying the items that have changed, deleted, and updated from the lists. React Keys are helpful...

3 minutes read.

ReactJS vs AngularJS

Difference between ReactJS and AngularJS AngularJS AngularJS is the JavaScript framework that is open source, and it is also used to build a dynamic web application. It is developed in 2009 by...

5 minutes read.

ReactJS Tutorial

ReactJS Introduction React Tutorial helps you to understand the basic and some advanced concepts of ReactJS. As of now, it is the essential front-end library that is developed by a...

3 minutes read.

React Component Life-Cycle

React Component Life-Cycle In ReactJS, the creation process of every component includes several lifecycle methods. These methods, together stated as component's lifecycle. Four phases of the component's life cycle are as...

4 minutes read.

Difference Between State and Props in React

Comparison between State and Props State The state is an updatable structure which is used for containing data or information about the component. The state in a component can be changed over...

2 minutes read.

React Higher-Order Components

React Higher-Order Components In short form, Higher-Order Components are represented as HOC. The Higher-order component is an advanced technique to use component logic. HOC is a function that takes the component and returns the new...

2 minutes read.

Difference Between React Flux and MVC

React Flux vs MVC MVC MVC is an acronym of 'Model View Controller.' It is the architectural pattern that is used to develop the user interface. It has three different logical components: The...

2 minutes read.

React Map

React Map The map() is the standard function of JavaScript, which can be called at any array. The map() method is used for traversing and displaying a list of the similar objects of...

2 minutes read.

React CSS

What is React CSS React CSS is used to provide the style to the React applications. The style attribute adds dynamically-computed styles at render time, and it is one of the most used...

5 minutes read.

React Hooks

React Hooks The Hooks were introduced in React 16.8. By using React Hooks, you can use the state and other features of the React without writing a class. Hooks do not work within the classes....

5 minutes read.