# React Router: Routing Mechanism in ReactJS

571

When designing a website, it is essential to be able to load different pages or modules, or to navigate to another page as per the context. React Router is the tool that supports these tasks. When implementing React Router, you may come across some issues and common problems. In this blog, we will talk about routing techniques and the underlying mechanisms.

React is an extremely popular library used to create single page applications (SPAs). We can have multiple views and components in the same page, therefore, to navigate through the whole application we need to use React Router.

In this post we will focus on the problems involved in using React Router, and will help you to understand the solutions.
You will learn the following:

1. Introduction
2. Basic Routing
3. How Routing Works / Routing Mechanism
4. Components in React Router and their explanation
5. Installation and Steps
6. Source Codes and Snippets
7. Challenges and Debugging
8. Conclusion

In this blog, we are using react-browser-router 2.1.2. You can check the official documentation here.
In the official documentation and the API, it is mentioned as the Browser Router, but we will use the word “Router” as it can be technically aliased.

## 1. Introduction: React Router (Browser Router)

React does not provide the facility of routing when we create the react app initially. We must install it manually in our application using a package manager (npm or yarn). Later we will learn how to enable routing in our React application, but before that we need to understand the core concepts.

Whenever a user changes the URL of the website, an HTTP request is sent to the server. The server recognizes the request and returns some responses, which can be a webpage or data in some forms (JSON objects, texts etc.)  The user may be redirected to another page and some other component in the same page may be loaded.

Let us take an example – when a user types a URL “localhost:3000/home”, the home page of the website should open; similarly, if the user types “localhost:3030/contact” then the contact page of the website should open. Also, if a user types some random or invalid URL, an error page or some error message should appear.

React Router makes it easier for the developers to implement this approach very effectively.

## 2. Basic Routing

The main task of routing is to load a specific page on targeting a specific URL or path. Loading a specific page on hitting a specific URL is called basic routing. It is quite easy to jump to another page, but it can get complicated when we try to render the components inside the same page. In this state, the page does not get refreshed and therefore there is less interaction with the server; and the performance of the application is increased as the server-side rendering is reduced.

## 3. How Routing Works / Routing mechanism

When we implement router in our react application, we are either looking to move to another page or load other components in the same page. To move to another page, we usually use Link inside the browser router. To load a component inside the same page, we use Route and specify the path and the component name.

Inside the Router, we use Switch to switch between the different routing paths.

We can use Link and Route together to load a particular component.

Route is for a specific path and a particular component. Therefore, whenever a particular path is triggered, the associated component must be rendered. To use the components, we need to import them in the same file where we are using the Router.

## 4. Components in React Router and their explanation

• <BrowserRouter> and <HashRouter>
To handle the static requests, we use HashRouter and to handle the dynamic requests, we use BrowserRouter. We will focus on BrowserRouter in the later steps. A BrowserRouter uses regular URLs.
• <Route> and <Switch>
Switch gives us the facility to switch between the different Routes. If no matching Route is found then the Switch renders nothing.
To create a link in our application, react provides a Link component. On the other hand, we can say that whenever we use the Link component simply <a> (an Anchor) is rendered in the HTML document. NavLink is a special type of Link. If we want to force a particular navigation, we can use Redirect.

## 5. Installation and the steps

You must be clear with the fact that when we create a react app, the browser router is not pre-installed. So, we need to add it in the application by using npm. To implement the routing in our application, first we will create an app and make some required changes in the further steps. Let us do this from scratch.

These are the essential steps which we can follow:

Step #1 Create a react App:

npx create-react-app my-app

If you have npm version 6+ then you can simply type

npm init react-app my-app

Step #2 Move to the Directory

cd my-app

Step #3 Launch the app

npm start

Step #4 Add Browser Router in our application

npm install --save react-router-dom

Step #5 Go to package.json and verify that the Browser Router is installed in our app

## 6. Source codes and snippets

Now our basic project is ready and we have successfully added the Browser Router package in our application. We need to import the relevant API from the react-router-dom library to make it work.

Let us move ahead and implement the rest of the steps:

Step #6 Remove the unnecessary codes from the App.js. We have the following codes now:

import React from 'react';
import './App.css';
function App() {
return (
<div className="App">
</div>
);
}
export default App;

Step #6 Create three JS files - Home.js, Contact.js and Feedback.js

import React from "react";
const Home = () => {
return (
<div>
<h 1>This is Home Page!</h1>
</div>
);
};
export default Home;
import React from "react";
const Contact = () => {
return (
<div>
<h1>This is Contact Page!</ h1>
</div>
);
};
export default Contact;
import React from "react";
const Feedback = () => {
return (
<div>
<h1>This is Feedback Page!</ h1>
</div>
);
};
export default Feedback;

Step #7 Import all the files in App.js file and start the app. You will find this output on the browser:

import React from 'react';
import './App.css';
import Home from './Home';
import Contact from './Contact';
import Feedback from './Feedback';
function App() {
return (
<div className="App">
<Home/>
<Contact/>
<Feedback/>
</div>
);
}
export default App;

Step #8 Now we can add the Routing part, and make some changes in the App.js

import React from "react";
import "./App.css";
import Home from "./Home";
import Contact from "./Contact";
import Feedback from "./Feedback";
import { BrowserRouter, Route, Link } from "react-router-dom";
function App() {
return (
<div className="App">
<BrowserRouter>
<div style={{ display : "flex"}}>
<li>
</li>
<li>
</li>
<li>
</li>
</div>
<Route path="/" exact component={Home} />
<Route path="/contact" component={Contact} />
<Route path="/feedback" component={Feedback} />
</BrowserRouter>
</div>
);
}
export default App;

Explanation: Look at the App.js file carefully. We have added the Link and Route inside the Browser router which says that whenever a user clicks on the link, it renders a specific component from the given path which we have mentioned in the Route.

By default, the home page is selected. Do not forget to put exact keywords (parameters) for the home Route as it disables the partial matching for a route. You can play around with the code and find out some interesting observations.

You can see in the address bar that whenever we click on the Contact and Feedback link, their respective URLs are reflected in the address bar. You can manually fill the same URL and trigger it, and it loads the respective pages. It is called basic or simple routing.

## 7. Challenges and debugging

I have gone through other blogs and tutorials where I have seen that they have aliased the BrowserRouter to Router. So do not get confused with this term. Both are similar and I am sure that you are aware about the Aliases for the packages.
You might face issues while using the BrowserRouter, Link and Route and therefore make sure that the package is installed. You can verify it in the package.json file.

Make sure that you provide the correct path and component name in the Route.

You can find the helpful documentation and resources here.

Conclusion

It is amazingly easy to use React Routing in your applications. It makes the UI more appealing and dynamic. You must specify the correct path and the respective components in the route component to make it work correctly. Before implementing the approaches, a basic understanding of the component and the hierarchy of the react components is necessary. There may be changes in the API or in the versions, therefore it is always better to use the official documentation to understand the usage.

### KnowledgeHut

Author

KnowledgeHut is an outcome-focused global ed-tech company. We help organizations and professionals unlock excellence through skills development. We offer training solutions under the people and process, data science, full-stack development, cybersecurity, future technologies and digital transformation verticals.
Website : https://www.knowledgehut.com