Easy Examples of React Routing Complete Guide 2022

Introduction

If you are a web developer then you are most probably familiar to work with React which is a JavaScript library used for building user interfaces. In this article, we are going to cover everything you need to know about React Routing.

React Routing is a feature that allows users to jump between different parts of a web-based application when that user clicks on a URL or an element, especially buttons, icons, or images in a web browser within the application.

Prerequisites

There are some libraries and software you need to know and download to your machine before you react to routing.

  1. Node and NPM
  2. Basic React Knowledge
  3. Text Editor

Download Visual Studio Code from the below link for Text Editor

VS Code- https://code.visualstudio.com/download

Routing in React

React Routing is an operation by which the browser URL is kept in sync with what’s being rendered on the page, the standard library used in it is React Router. Especially among JavaScript Developers, it is one of the most famous libraries. It allows navigation for different components in react application and also allows changing browser URL and keeping the UI in sync with it.

Main Components of React Routing

The main components in Routing in React are as follows:- 

  • Link
  • Route
  • Switch

Link

This Component is used to create links to different routes and it helps to implement navigation through the application. It works as an anchor tag. It uses the ‘to’ prop to help the links to navigate to the described location by it.

Example

<div className="App">
    <ul>
      <li>
        <Link to="/">Home</Link>
      </li>
      <li>
        <Link to="/about">About Us</Link>
      </li>
      <li>
        <Link to="/contact">Contact Us</Link>
      </li>
    </ul>
</div>

Route

It is the conditionally shown component and it renders the UI when the path matches the given URL. It is specially used to establish the connection between the Component’s UI and The URL. You have to add the code in the app.js to include routes to the program.

Example

<Route exact path='/' component={Home}></Route>
<Route exact path='/about' component={About}></Route>
<Route exact path='/contact' component={Contact}></Route>

Now let’s discuss the process associated with Route Component used in Routing.

  • Exact
    It is used in react-navigation and it matches the exact value of the given URL in the browser.
  • Path
    In the react-navigation, it specifies the pathname assigned to the component
  • Component
    The component in react-navigation refers to the component to render on matching the path.

Switch

The switch component will allow you to render the first route that matches the location instead of rendering all matching routes through the app. It is used to render a single component and apart from that, it can also bind all the routes through the Components.

Example

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

Types of Routing in React

The types of routing in React are as follows:- 

  1. Memory Router
  2. Browser Router
  3. Hash Router

Memory Router

Memory Router saves the history of the URL in the memory except for saving it in the browser. Without altering the URL in the browser it maintains the history of that URL in the memory. It is useful for tests and non-browser environments like React.

The Syntax used for Memory Router

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

Memory Router Example

import React, { Component } from 'react';
import { MemoryRouter as Router, Route, Link, Switch } from 'react-router-dom';
import Home from './component/home';
import About from './component/about';
import Contact from './component/contact';
import './App.css';
class App extends Component {
render() {
    return (
            <Router>
        <div className="App">
            <Link to="/">Home</Link>
            <Link to="/about">About Us</Link>
            <Link to="/contact">Contact Us</Link>
                  <Switch>
            <Route exact path='/' component={Home}></Route>
            <Route exact path='/about' component={About}></Route>
            <Route exact path='/contact' component={Contact}></Route>
            </Switch>
        </div>
                </Router>
        );
      }
}
export default App;

Browser Router

It is one of the popular routers in React Routing. Browser Router uses the HTML5 language to keep the API history and the UI in sync with the URL and it. It is specially used to handle dynamic URLs.

The Syntax used for Browser Router

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

Browser Router Example

import React, { Component } from 'react';
import { BrowserRouter as Router, Route, Link, Switch } from 'react-router-dom';
import Home from './component/home';
import About from './component/about';
import Contact from './component/contact';
import './App.css';
class App extends Component {
render() {
    return (
            <Router>
        <div className="App">
            <Link to="/">Home</Link>
            <Link to="/about">About Us</Link>
            <Link to="/contact">Contact Us</Link>
                                                <Switch>
                <Route exact path='/' component={Home}></Route>
                <Route exact path='/about' component={About}></Route>
                <Route exact path='/contact' component={Contact}></Route>
            </Switch>
        </div>
            </Router>
        );
      }
}
export default App;
https://application.com/dashboard   /* BrowserRouter */

Hash Router

Using the URL in the browser it uses its hash portion to keep the UI in sync with it. It basically builds URLs with hash and it is used to handle the static request from the browser.

The Syntax used for Hash Router

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

Hash Router Example

import React, { Component } from 'react';
import { HashRouter as Router, Route, Switch, Link } from 'react-router-dom';
import Home from './component/home';
import About from './component/about';
import Contact from './component/contact';
import './App.css';
class App extends Component {
render() {
    return (
            <Router>
        <div className="App">
            <Link to="/">Home</Link>
            <Link to="/about">About Us</Link>
            <Link to="/contact">Contact Us</Link>
                                                <Switch>
                <Route exact path='/' component={Home}></Route>
                <Route exact path='/about' component={About}></Route>
                <Route exact path='/contact' component={Contact}></Route>
            </Switch>
        </div>
            </Router>
        );
      }
}
export default App;
https://application.com/#/dashboard /* HashRouter */

Create Routing in React

If you want to create Routing in React then you need to follow some steps, the steps are as follows:-

  1. Create React Application
  2. Install React Router dependency
  3. Create Components
  4. Add Routes for Components

First of all, we have to set up the React Router.

To do that, You have to follow some steps and some codes to run on your computer.

You can check that which version of node and npm version has been installed to do that write the below code on your computer.

node -v
> 12.19.0

npm -v
> 6.14.8

Step 1: Creating a React Application

First of all, you have to create an app named ‘aspire-route-example’ with the command below.

npx create-react-app aspire-router-example

After this change into the newly created directory

cd react-router-demo

Step 2: Installing the React Router Dependencies

There is an easy way to install the React Router Dependencies in your local machine. To do that you have to write the command mentioned below in your terminal.

npm install react-router-dom

Then start the server with the following code

npm run start

Step 3: Creating Components for Routing

In this step we have to create some components for Routing using React and These components are HOME, ABOUT, and CONTACT. The Code is mentioned below

For Home.js

import React from "react";
function Home() {
  return (
    <div>
      <h1> Welcome to Homepage </h1>
      <p>
        Read react articles on &nbsp;
        <a href="https://www.aspiresoftware.in/blog">Aspire Blog </a>
      </p>
    </div>
  );
}
export default Home;

For About.js

import React from "react";
function About() {
  return <h1> About us page </h1>;
}
export default About;

For Contact.js

import React from "react";
function Contact() {
  return <h1> Contact Page </h1>;
}
export default Contact;

Step 4: Adding the Routes for the Components

Now we have to add routes for the components created and we will set each route for the components individually. The codes are mentioned below.

For App.js

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

After the app starts we will use three clickable links to alter the route through the App and the rest code is mentioned below.

For App.js

import "./App.css";
import { BrowserRouter as Route, Router,, Link } from "react-router-dom";
import React from "react";
import Home from "./Components/Home";
import About from "./Components/About";
import Contact from "./Components/Contact";
function App() {
  return (
    <div className="App">
      <Router>
        <div className="App">
          <ul>
            <li>
              <Link to="/">Home</Link>
            </li>
            <li>
              <Link to="/about">About Us</Link>
            </li>
            <li>
              <Link to="/contact">Contact Us</Link>
            </li>
          </ul>
        </div>
        <Route exact path="/" component={Home} />
        <Route exact path="/about" component={About} />
        <Route exact path="/contact" component={Contact} />
      </Router>
    </div>
  );
}
export default App;

Output:

The output of the entire source code is mentioned below

Easy Examples of React Routing Complete Guide 2022 1

Nested Routing

To understand nested Routing we must have a better knowledge of the Route.

The most recommended method of rendering in Route is to use `children` elements and there are some others methods too to render in the router. These are basically used for supporting apps that were built before hooks were introduced:

  • `component`: After the URL is matched the router creates a component by using `React.createElement`
  • `render`: This is especially handy for inline rendering cause when the location matches the route path the `render` prop expects a function and that returns an element.
  • `children`: it is similar to `render` so in that it returns a react component but the `children`, it is rendered simultaneously until whether the path is matched or not.

Path and Match

The router should match the portion of the URL and it is identified by the `path` prop. It turns a path string into a regular expression and it does that by using the Path-to-RegExp library to match it against the current location.

After successfully matching the path with the location it creates an object named `match` object. It contains more information about the URL and the path. This information is accessible by its properties which are listed below.

  • `match.url`: This is especially useful to build nested `<Link>` components and it’s a string that basically returns the matched portion of the URL.
  • `match.path`: It is used to build nested `<Route>` components and it returns the route’s path string which is `<Route path==””>`.
  • `match.isExact`: It is a boolean and it returns true if the match was exact without any trailing characters.
  • `match.params`: It is an object which contains key pairs from the URL handled by the Path-to-RegExp package.

Implicit passing of Props

When you are using the `component` prop to render a route the `match`, `location`, and `history` route props are passed to the component but using the route rendering pattern it is different.

For Example,

Use this component:

const Home = (props) => {
  console.log(props);

  return (
    <div>
      <h2>Home</h2>
    </div>
  );
};

Now render the route will be like this:

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

This will log like this:

{
  history: { … }
  location: { … }
  match: { … }
}

But instead if we use render route like the following:

<Route exact path=”/”><Home /></Route>

This will log like this:

{}

Advantages of Routing in React

These are the advantages below for using Routing in React

  • When we use Routing it gets easier to set the browser history as compared to manually.
  • It will allow the links to navigate the internal links through React Application.
  • Routing uses Rendering in the browser by the switch feature which is very much efficient.
  • There is a need for only a Single Child Element.
  • In Routing every Component is specified.
  • React router helps us to easily handle the nested views and the progressive resolution of views.

Conclusion

So moreover we tried to cover up everything related to react routing and now you can have a complete idea about the react routing which will help you out in your further projects. Start doing everything practically so that you can get hands-on experience on react routing so that you can do any of the complex projects 

To conclude everything React is a popular and useful language and you came to know about React Routing, React Components, and The Types of Routing in React in this blog. Also, you covered up its syntax and use of React routing and how to build a Routing in React with the source code here.

Source:- v5.reactrouter.com

Scroll to Top