React Router-DOM

In the world of web development, React.js has emerged as a very powerful library to create websites, and React Router DOM is another important library in React that allows navigation and routing in React applications. In this blog, you are going to learn everything about React Router, its features, uses, and most importantly, how to set up routes using React Router in your web development projects.

Table of Contents:

React Router

React Router is an important library in React that allows navigation (the process of moving between different pages) and routing for single-page applications. It allows users to navigate between pages, creates a perfect user experience, and creates interactive user interfaces.

Features of React Router

Here are some of the important features of React Router:

  • Dynamic Routing: React Router helps in creating routes for dynamically changing parameters. It is one of the important features of React Router that is used in most real-world projects.
  • History Management: It can take a record of the states, thus providing full control over browser history and navigation.
  • Protected Routes: If you want to stop users from accessing any route without authentication, then React Router helps you to achieve this.
  • Lazy Loading: React Router helps in increasing the performance of applications by loading components only when required.
  • Declarative Routing and Nested Routes: Here, routes are defined using JSX (JavaScript XML), making code more readable. Also, it supports nested routes.
From HTML to Full-Stack Development, Learn Everything You Need to Succeed.
Master Web Development – Join Our Course!
quiz-icon

Core Components of React Router

Here are some of the core components of the React Router library, which are important to know before working with the React Router:

BrowserRouter and HashRouter

In React, routers are of three types:

  1. BrowserRouter
  2. HashRouter
  3. MemoryRouter

BrowserRouter is the most commonly used router in React. It uses the browser history API, which means you can navigate between routes without a full page reload. It is the best choice for modern web applications because it helps in smooth navigation.

HashRouter uses the hash URL ( # ) for navigation instead of directly modifying the browser history. It appends a # before the route (Intellipaat.com/#/about), making it best for static websites hosted on platforms like GitHub Pages.

Routes and Route

In React Router, Routes and Route are fundamental components used to define paths for routing and navigation. The Routes component works as a container for multiple Route components. The Routes component ensures that no similar routes are available at a time. While Route is used to define a unique URL path for rendering each component when the path matches.

Link is used for navigation without reloading the page, while NavLink is an enhanced version of Link in React Router that helps in adding a CSS class automatically when the link is active.

Setting Up a React Project

Before learning more about React Router, you need to set up a React project on your system. Let’s discuss the steps in detail:

Step 1: Install Node.js on your system

Before setting up a React project, it’s important to download Node.js on your system. Here are the steps to install Node.js:

  1. Go to your browser
  2. Type “node.js download” in the search bar and click on the official link node.org to download Node.js on your system.
  3. After downloading Node.js on your system, check for it by opening a command prompt and typing this command:
npm -v
node -v

Step 2: Create a folder and set up a React project

Your next step is to create a folder wherever you want it and open that folder in your personalized code editor (VScode recommended). Now, open a terminal in it and type the following commands:

npm create vite@latest

Type the name of the folder (react-router-intellipaat) and choose React as the library and JavaScript as the variant, and press Enter.

cd react-router-intellipaat
npm install
npm run dev

Execute all these commands one by one, and now your React project is created successfully. After setting up the React project, check your dependencies in the package.json file. You can see that only react and react-dom are installed. Thus, you have to install the react-router-dom dependency.

React Project 1

//package.json

"dependencies": {
    "react": "^19.0.0",
    "react-dom": "^19.0.0"
  },

  "devDependencies": {
    "@eslint/js": "^9.21.0",
    "@types/react": "^19.0.10",
    "@types/react-dom": "^19.0.4",
    "@vitejs/plugin-react": "^4.3.4",
    "eslint": "^9.21.0",
    "eslint-plugin-react-hooks": "^5.1.0",
    "eslint-plugin-react-refresh": "^0.4.19",
    "globals": "^15.15.0",
    "vite": "^6.2.0"
}

Installing React Router and Creating Routes

Now, you have to install React Router in your project by writing the following commands in the terminal:

npm install react-router-dom

This time, when you check the installed dependencies in the package.json file, you will find that react-router-dom is installed in your project. Now, you’re able to use its methods and hooks.

"dependencies": {
    "react": "^19.0.0",
    "react-dom": "^19.0.0",
    "react-router-dom": "^7.4.0"
  }

Example: Let’s understand React Router by creating routes for different pages in your React project. Here is the project structure and code:

React Project 2

//App.jsx File

import React from "react";
import {BrowserRouter, Routes, Route} from 'react-router-dom'
import { Home } from "./Pages/Home";
import { About } from "./Pages/About";
import { Contact } from "./Pages/Contact";
function App(){
    return (
        <BrowserRouter>
            <Routes>
                <Route path="/" element={<Home/>}/>
                <Route path="/about" element={<About/>} />
                <Route path="/contact" element={<Contact/>} />
            </Routes>
        </BrowserRouter>
    )
}
export default App;

//Home.jsx File

import React from 'react'
import { Link } from 'react-router-dom'
export const Home = () => {
  return (
    <>
    <nav>
      <ul>
        <li>
            <Link to="/">Home</Link>
        </li>
        <li>
            <Link to="/about">About</Link>
        </li>
        <li>
            <Link to="/contact">Contact</Link>
        </li>
      </ul>
    </nav>
    <h1>Learn React From Intellipaat.</h1>
    </>
  )
}

//About.jsx File

import React from 'react'
export const About = () => {
  return (
    <h1>About Page</h1>
  )
}

//Contact.jsx File

import React from 'react'
export const Contact = () => {
  return (
    <h1>Contact Page</h1>
  )
}

//index.css File

*{
  margin: 0%;
  padding: 0%;
  box-sizing: border-box;
}
html, body{
  height: 100%;
  width: 100%;
}
ul{
  height: 50px;
  list-style: none;
  display: flex;
  align-items: center
  gap: 20px;
  margin-left: 10px;
}
h1{
  color: orangered;
  margin-left: 10px;
  font-weight: 500;
}

Output:

React Project

Explanation: In this example, you are creating routes for the Home, About, and Contact pages as /, /about, and /contact. Clicking on any <li> in the navbar navigates you to the specific page without reloading the full page(only the changed HTML element is reloaded). You can also navigate back because, internally, React Router uses history.pushState() for navigation.

React Router Hooks

React Router hooks are defined as special functions that are used to interact with the routing system. Here are some commonly used React Router hooks:

useParams Hook

The useParams hook allows you to retrieve query parameters from the URL. This is useful when you’re working with dynamic routes where you have to display different data for different users.

Example: Displaying user profile information based on ID.

//App.jsx File

import React from "react";
import {BrowserRouter, Routes, Route} from 'react-router-dom'
import { Home } from "./Pages/Home";
import { UserProfile } from "./Pages/UserProfile";
function App(){
    return (
        <BrowserRouter>
            <Routes>
                <Route path="/" element={<Home/>}/>
                <Route path="/user/:id" element={<UserProfile/>}/>
            </Routes>
        </BrowserRouter>
    )
}
export default App;

//UserProfile.jsx File

import React from 'react'
import { useParams } from 'react-router-dom'
export const UserProfile = () => {
  let {id} = useParams();
  return (
    <h1>User ID : {id}</h1>
  )
}

Output:

React Router Hooks

Explanation: In this example, you are using useParams to display a dynamically changing parameter id. The user can pass any value as an ID in the URL. But the useParams hook detects the query parameter and displays it in the window.

useHistory Hook

In earlier versions of React Router (before v6), the useHistory hook was used for performing navigation. But in React Router version 6, the useNavigation hook is used instead of useHistory.

useHistory allows navigation between pages without reloading and provides various methods like .push(), .replace(), and .goBack() for forward and backward routing. Now, it is not used in projects.

useNavigation Hook

In React Router version 6, useNavigate is used for navigation instead of useHistory, which is deprecated now. It also works in a similar way to useHistory. It also provides cleaner and shorter syntax for navigation.

Example:

//App.jsx File

import React from "react";
import {BrowserRouter, Routes, Route} from 'react-router-dom'
import { Home } from "./Pages/Home";
import { UserProfile } from "./Pages/UserProfile";
function App(){
    return (
        <BrowserRouter>
            <Routes>
                <Route path="/" element={<Home/>}/>
            </Routes>
        </BrowserRouter>
    )
}
export default App;

//Home.jsx File

import React from 'react'
import { useNavigate } from 'react-router-dom';
export const Home = () => {
  let navigate = useNavigate();
  function aboutRoute() {
    navigate('/about');
  }
  return (
    <>
      <h1>Learn React From Intellipaat.</h1>
      <button onClick={aboutRoute}>Go About</button>
    </>
  )
}

Output:

useNavigation Hook

Explanation: In this example, you’re using the useNavigate hook instead of useHistory (deprecated) to navigate between pages.

useLocation Hook

The useLocation hook in React Router is used to access the current URL and extract information about the user’s navigation history. It is useful for getting the current pathname and accessing the query parameter.

Example: Displaying current page URL

//App.jsx

import React from "react";
import {BrowserRouter, Routes, Route} from 'react-router-dom'
import { Home } from "./Pages/Home";
import { UserProfile } from "./Pages/UserProfile";
function App(){
    return (
        <BrowserRouter>
            <Routes>
                <Route path="/" element={<Home/>}/>
            </Routes>
        </BrowserRouter>
    )
}
export default App;

//Home.jsx

import React from 'react'
import { useLocation } from 'react-router-dom';
export const Home = () => {
  let location = useLocation();
  return (
    <>
      <h1>Learn React From Intellipaat.</h1>
      <p>You're currently on page: {location.pathname}</p>
    </>
  )
}

Output:

useLocation Hook

Explanation: In this example, you’re using the useLocation hook for getting information about the current URL. Like in the above example, you’re at / (root URL).

Uses of React Router

Here are some of the use cases of the react-router-dom library:

  1. Creating Protected Routes and Authentication: React Router helps you create protected routes for your web application. Protected routes ensure that users can only access certain pages if they are logged in. For example, if a user is not authenticated, they should be redirected to the login/signup page before accessing the dashboard.
  2. Conditional Navigation: React Router allows you to perform conditional navigation, which means navigation based on user actions such as logging out or checking permission.
  3. Lazy Loading with React Router: Lazy Loading helps to improve the performance of the application by loading the component only when needed, rather than loading them all at once.

Get 100% Hike!

Master Most in Demand Skills Now!

Conclusion

React Router is an important library for making web development projects. It helps you in everything from making simple navigation to making dynamic routes, protected routes, and increasing performance with lazy loading. By knowing these things, you’re able to make single-page applications easily.

React Router-DOM – FAQs

Q1. What is a React Router used for?

React Router is used to handle navigation in single-page applications without reloading the full page. It also helps developers in creating dynamic and protected routes.

Q2. How many types of routers are in React?

React Router has various types like BrowserRouter, HashRouter, MemoryRouter,  and StaticRouter.

Q3. Is React Router a server?

No, React Router is purely a client-side routing library, not a server.

Q4. What is JSX in React?

JSX stands for JavaScript XML and is a syntax extension for JavaScript that allows us to write HTML code inside React components.

Q5. What are React Hooks?

React Hooks are defined as special functions that allow developers to manage state and side effects without writing a new class component. useState and useEffect are some examples of hooks.

Q6. What is reconciliation in React?

Reconciliation in React is defined as the process of updating the DOM by only re-rendering changed components.

About the Author

Technical Research Analyst - Full Stack Development

Kislay is a Technical Research Analyst and Full Stack Developer with expertise in crafting Mobile applications from inception to deployment. Proficient in Android development, IOS development, HTML, CSS, JavaScript, React, Angular, MySQL, and MongoDB, he’s committed to enhancing user experiences through intuitive websites and advanced mobile applications.

Full Stack Developer Course Banner