React.js

Dynamic routing in React-js application

Welcome readers, in this tutorial, we will implement dynamic 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 react-js 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 react-js 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. 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 – get-fetch-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. Dynamic 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 { BrowserRouter } from "react-router-dom";
import App from "./App";
import "./index.css";
import reportWebVitals from "./reportWebVitals";

const root = ReactDOM.createRoot(document.getElementById("root"));
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 Create components

Create a folder named components in the src folder and add three components called User.js, Home.js, and PageNotFound.js to the folder. You can download the files from the Downloads section and are free to change the component file code as per your wish.

2.1.2.1 Home.js component

Add the below code to the component file. The component is responsible for showing the default page of the application.

Home.js

import React from "react";

const Home = () => {
  return (
    <div>
      <h1>home page landed</h1>
    </div>
  );
};

export default Home;
2.1.2.2 PageNotFound.js component

Add the below code to the component file. The component is responsible for showing the 404 error page if the entered URL does not exist.

PageNotFound.js

import React from "react";

const PageNotFound = () => {
  return (
    <div>
      <h1>404 page not found</h1>
    </div>
  );
};

export default PageNotFound;
2.1.2.3 User.js component

Add the below code to the component file. The useParams in the import statement will return the key/value pairs object of the dynamic value from the current URL that is matched by the route path. The dynamic value from the current URL will be shown as a message on the HTML page.

User.js

import React from "react";
// if you're using useParams ensure that component and file name are in capitals as per reactjs guidelines
import { useParams } from "react-router-dom";

const User = () => {
  let { userName } = useParams();

  let today = new Date();
  let timestamp =
    today.getDate() +
    "-" +
    (today.getMonth() + 1) +
    "-" +
    today.getFullYear() +
    " " +
    today.getHours() +
    ":" +
    today.getMinutes() +
    ":" +
    today.getSeconds() +
    ":" +
    today.getMilliseconds();

  return (
    <div>
      <h1>
        {userName} has landed on {timestamp}
      </h1>
    </div>
  );
};

export default User;

2.1.3 Import Routes and create navigation links

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 Home from "./components/Home";
import PageNotFound from "./components/PageNotFound";
import User from "./components/User";

function App() {
  // to create a dynamic link based on the name
  const names = ["Adam", "Eve", "John", "Chris"];

  return (
    <div className="App">
      <>
        <h1>ReactJs: Dynamic Routing Demo</h1>
        <nav>
          <ul>
            <li key="0">
              <Link to="/">Home</Link>
            </li>
            {names.map((name, index) => (
              <li key={index + 1}>
                <Link to={`/user/${name}`}>User {index + 1}</Link>
              </li>
            ))}
          </ul>
        </nav>

        <Routes>
          {/* responsible to show the default or the index page */}
          <Route path="/" element={<Home />}></Route>
          {/* responsible to show user page with dynamic username */}
          <Route path="/user/:userName" element={<User />}></Route>
          {/* only match this when no other routes match */}
          <Route path="*" element={<PageNotFound />} />
        </Routes>
      </>
    </div>
  );
}

export default App;

3. Run the React Application

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.

Fig. 3: Application run

4. Demo

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

Fig. 4: Application demo

The home page will show the user’s link and you can click on each link to see a different message based on the username. The page responsible to show the message is retrieved from the User.js component and it retrieves the name value from the current URL.

Fig. 5: User 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 dynamic routing. You can download the source code from the Downloads section.

6. Download the Project

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

Download
You can download the full source code of this example here: Dynamic routing in react-js 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
Inline Feedbacks
View all comments
Back to top button