React.js

Routing in react-js application

Welcome readers, in this tutorial, we will implement routing in react-js with the help of the react-router library.

1. Introduction

React is a flexible javascript library responsible for building reusable UI components. It is an open-source component-based frontend library responsible only for the view part of an application and works in a virtual document object model. But before that let us take a look at the differences between angular and react –

AngularReact
Complete frameworkLibrary
Object-oriented programmingExtension to the javascript library and its internal architecture is based on jsx
Based on the model view controller and real document object modelBased on the virtual document object model

1.1 What is Routing and React router?

Routing is a mechanism through which requests are routed to the code that handles them. React routing enables the navigation across different view comments of a reactjs application by changing the url in the browser and keeping the UI synced with the url. React router is a fully featured client and server-side routing library for reactjs and is helping in building user interfaces by defining routes in a declarative style. It consists of two components i.e. –

  • BrowserRouter – Used for handling the dynamic url
  • HashRouter – Used for handling the static request

1.2 Setting up dependencies

To play with react let us set up some of the required dependencies.

1.2.1 Setting up Node.js

To set up Node.js on windows you will need to download the installer from this link. Click on the installer (also include the NPM package manager) for your platform and run the installer to start with the Node.js setup wizard. Follow the wizard steps and click on Finish when it is done. If everything goes well you can navigate to the command prompt to verify if the installation was successful as shown in Fig. 1.

Fig. 1: Verifying node and npm installation

1.2.2 Setting up react js project

Once the Nodejs setup is successful we will use the below command to install the react library and set up the project to demonstrate routing in React. Do note that the npx package is available with the npm 5.2 version and above.

Create project structure

$ npx create-react-app routing-app

The above command will take some time to install the react library and create a new project named – routing-app as shown below.

Fig. 2: Project structure

1.2.3 Setting up React Router Dom

Once the project is created successfully navigate to the project’s root directory and run the below npm command to install the react-router library into the routing-app project. The react-router-dom package is used in web applications.

Installing router dom

$ npm i react-router-dom

Once the module is installed successfully it will be added to the package.json file under dependencies.

2. Routing in react js application

To set up the application, we will need to navigate to a path where our project will reside and I will be using Visual Studio Code as my preferred IDE.

2.1 Setting up the react code

To understand a practical implementation let us go through some hands-on exercises.

2.1.1 Importing BrowserRouter

Import BrowserRouter component from the react-router-dom package in the index.js file and wrap the App component under the BrowserRouter component.

Index.js

import React from "react";
import ReactDOM from "react-dom/client";
import "./index.css";
import App from "./App";
import reportWebVitals from "./reportWebVitals";
// using browser router as app only supports modern browsers
import { BrowserRouter } from "react-router-dom";

const root = ReactDOM.createRoot(document.getElementById("root"));
// wrapping app component inside browser router
// router component can only have one child element.
root.render(
  <React.StrictMode>
    <BrowserRouter>
      <App />
    </BrowserRouter>
  </React.StrictMode>
);

// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
reportWebVitals();

2.1.2 Creating components 

Create a folder named components in the src folder and add three components called About.js, Home.js, and PageNotFound.js to the folder.

About.js

import React from "react";

const about = () => {
  return (
    <div>
      <h1>about</h1>
    </div>
  );
};

export default about;

Similarly, create the other component file and add the required code to it or you can download the source code from the Downloads section. You are free to change the component file code as per your wish.

2.1.3 Import Routes and create navigation links in react

Import Routes and Route components from react-router-dom in the App.js file.

  • Use path property to define url
  • Use element property to define the corresponding component

App.js

import { Link, Route, Routes } from "react-router-dom";
import "./App.css";
// importing components
import About from "./components/About";
import Home from "./components/Home";
import PageNotFound from "./components/PageNotFound";

function App() {
  return (
    <div className="App">
      <>
        <nav>
          <ul>
            <li>
              <Link to="/">Home</Link>
            </li>
            <li>
              <Link to="/about">About</Link>
            </li>
          </ul>
        </nav>

        <Routes>
          <Route path="/" element={<Home />} />
          <Route path="/about" element={<About />} />
          {/* only match this when no other routes match */}
          <Route path="*" element={<PageNotFound />} />
        </Routes>
      </>
    </div>
  );
}

export default App;

3. Run the setup

To run the application navigate to the project directory and enter the following command as shown below in the terminal.

Run command

$ npm run start

The application will be started on the default port. In case the application does not get started on the default port you can change the port number as per your requirement. I have changed the default port to 2000.

4. Demo

The application will be started in the default browser as shown below and the default home page will be shown.

Fig. 3: Application run
Fig. 4: Application demo

You can either click on the navigation links or specify the /about keyword in the url to show the about page.

Fig. 5: About page

The page-not-found html page will be shown if the user specifies a url that is not mapped in the application. This page acts as a default 404 error page. That is all for this tutorial and I hope the article served you with whatever you were looking for. Happy Learning and do not forget to share!

5. Summary

In this tutorial, we created a react application and understood the application routing. You can download the source code from the Downloads section.

6. Download the Project

This was a tutorial to understand application routing in a react application.

Download
You can download the full source code of this example here: Routing in reactjs application

Yatin

An experience full-stack engineer well versed with Core Java, Spring/Springboot, MVC, Security, AOP, Frontend (Angular & React), and cloud technologies (such as AWS, GCP, Jenkins, Docker, K8).
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button