×

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

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 Fragments

React Fragments The fragments in React are introduced from the 16.2 and above versions. Fragments allow you to group a list of child elements without adding any extra node in the DOM. In React,...

2 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.

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.

Pros and Cons of ReactJS

Pros and Cons of ReactJS There are various advantages, and disadvantages of ReactJS are as follows: Benefits of ReactJS 1. Easy to Learn and Use: ReactJS is very easy to use and learn. It has a good...

3 minutes read.

React Conditional Rendering

React Conditional Rendering In React, the working of the conditional rendering is similar to the condition works in JavaScript. We use JavaScript operators for creating elements that represent the current state, and then the React...

3 minutes read.

React Native vs ReactJS

Difference between React Native and ReactJS React Native React Native is also an open-source JavaScript framework that is used for the development of a mobile application for iOS Android and Windows. It...

6 minutes read.

Features of ReactJS

ReactJS Features As of now, within the developers, ReactJS is gaining much popularity as the best JavaScript framework. It is crucial for the front-end ecosystem. There are some of the crucial features of ReactJS that are...

2 minutes read.

React Table

React Table The table represents an arrangement that organizes the information in the form of rows and columns. The table is mainly used for storing and displaying the data within a structured format. Features of...

2 minutes read.

React Error Boundaries

React Error Boundaries In the past, the errors of JavaScript within the components were used to corrupt the internal state of react and cause it to emit the cryptic errors on the next...

3 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 Props

React Props A prop is an abbreviation of ‘properties.' State and props are mainly different from each other because props are immutable. Props are the read-only components. It is the object that stores the attribute...

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 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 Lists

React Lists Lists are used for displaying the data in an ordered format and mainly used to display the menus on websites. The creating of lists in React is as similar...

2 minutes read.

React Redux

How to Use Redux with React Hooks It is an open-source library of JavaScript which is used for managing the application state. React uses the Redux to build the user interface....

5 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 Component API

React Component API It is a top-level API. It provides reusability to the code in the application and makes it completely individual. It has several methods for: Creating Elements.Transforming Elements.Fragments. Now, we are explaining the three...

2 minutes read.

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.