View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All

Routing in ReactJS Simplified: Essential Beginner-Friendly Examples!

By Pavan Vadapalli

Updated on Jul 02, 2025 | 21 min read | 42.57K+ views

Share:

Did you know that the uninstall rate of React remains steady at 1.5%? This low uninstall rate reflects React’s stability and the effectiveness of its component-based architecture in real-world applications.

Routing in ReactJS maps URLs to components, allowing pages to change instantly without full reloads. Imagine an e-commerce cart updating dynamically or a dashboard displaying live analytics, all without the need to refresh the page. React Router, used in 44% of React projects, is key to making this possible. With powerful features like nested routes and dynamic parameters.

In this guide, we’ll walk you through the core aspects of Routing in ReactJS, setting it up, implementing core features, and even securing routes step by step.

Struggling in front end technologies like ReactJS? Explore upGrad’s comprehensive online software development courses and start learning the most in-demand programming languages, frameworks, and technologies today!

Significance of Routing in ReactJS in Web Development

ReactJS routing, without prior knowledge, can be manually implemented using useState and JSX for conditional rendering. However, this approach is inefficient for large-scale applications like e-commerce. 

If you want to learn web development and understand the fundamentals of Routing in ReactJS, the following courses from upGrad can help you succeed, 

It can still serve as a boilerplate for understanding Routing in ReactJS, and a foundation for React Router. For example:

import React, { useState } from 'react';

function App() {
  const [page, setPage] = useState("products");
  const [cart, setCart] = useState([]); // Initialize cart as an empty array

  const routeTo = (newPage) => {
    setPage(newPage);
  };

  return (
    <div>
      <button onClick={() => routeTo("cart")}>Cart</button>
      {page === "cart" && (
        <Cart cart={cart} setCart={setCart} />
      )}
    </div>
  );
}

function Cart({ cart, setCart }) {
  return (
    <div>
      <h1>Your Cart</h1>
      {cart.length === 0 ? (
        <p>Your cart is empty.</p>
      ) : (
        <ul>
          {cart.map((item, index) => (
            <li key={index}>{item}</li>
          ))}
        </ul>
      )}
    </div>
  );
}

export default App;

Output:

1. Initial State:

  • The page will initially display a "Cart" button.
  • Since the cart is empty, clicking the "Cart" button will display a message: "Your cart is empty."

2. When Items Are Added:

  • If you add items to the cart array, those items will be displayed as a list inside the Cart component.

Explanation:

In this React app:

  • The useState hook is used to manage the state of the page (which determines which content is shown) and the cart (which stores the items in the cart).
  • When the user clicks the "Cart" button, the routeTo function is triggered, changing the page state to "cart" and displaying the Cart component.
  • Inside the “Cart” component, a conditional check is used to see if the cart is empty. If the cart array is empty, the message "Your cart is empty" is shown. Otherwise, the items in the cart are displayed as a list.

Example of what the output will look like:

Initial State:

[Button] Cart

After Clicking the Cart Button (Empty Cart):

Your Cart

Your cart is empty.

Or, if you have items in the cart:

Your Cart

- Item 1

- Item 2

- Item 3

Server-side routing causes full page refreshes with repeated data loading, leading to a poor user experience and slow load times. In contrast, client-side routing, like React Router, handles routing internally with JavaScript, rendering only the new component without a page reload.

This results in a smoother, more efficient UX, making it ideal for single-page applications.

Basic Routing 

Basic routing refers to directing network traffic between devices using simple, predefined paths. It plays a key role in network performance by minimizing delays and optimizing data flow.

React Router API

Browser Router or React Router API is the most popular library for routing in reactJS to navigate among different components in a React Application, keeping the UI in alignment with the URL.  

According to react-router official docs, “ React Router is a fully-featured client and server-side routing library for React, a JavaScript library for building user interfaces.” 

Various Packages in React Router Library

Coverage of AWS, Microsoft Azure and GCP services

Certification8 Months

Job-Linked Program

Bootcamp36 Weeks

There are 3 different packages for React Routing. 

  • react-router: This is the core package for routing in ReactJS applications. It includes all the fundamental routing functionalities used in both react-router-dom and react-router-native.
  • react-router-dom: Specifically designed for dynamic routing in ReactJS in web applications, this package is commonly used in React web projects.
  • react-router-native: It is used to implement dynamic routing in ReactJS in web applications.

Let’s understand how routing works, focusing on the underlying mechanisms that ensure efficient data delivery.

How Routing Works / Routing Mechanism

Routing involves navigating between pages on a website. React Router, part of Client-Side Routing, handles routing dynamically with Client-Side Rendering (CSR). 

In CSR, the server only handles data requests, while the client manages rendering and routing. Unlike traditional routing, which loads a new index.html for each page, CSR only returns one index.html for all routes.

Installation and the Steps for React Router

React Router is an essential library for managing navigation in a React application, enabling seamless transitions between different views or pages. It allows you to create dynamic, multi-page applications by mapping URL paths to specific components. By integrating React Router into your project, you can enhance user experience with easy navigation and dynamic content rendering.

Prerequisite for react-router dom install: 

1. You must have a react app created using create-react-app 

2. The react app must be running with dummy code to proceed with creating react app router 

React Router will help us make a dynamic navbar with different links to route on, resembling a blog application where every link routes us to a  different new page. 

Step 1: Run the following commands in terminal

npm install react-router-dom@6 
or 
yarn add react-router-dom@6 

Step 2: The package installs after the completion of npm and a message is received on the terminal varying with your system architecture.   

+ react-router-dom@6 
added 11 packages from 6 contributors and audited 1981 packages in 24.897s 
  
114 packages are looking for funding 
  run `npm fund` for details 
  
found 0 vulnerabilities

And that’s it, we are ready to route!

Also Read: Top 28 React Projects for Beginners in 2025 [Source Code Included]

Now let's come to the source code after the fundamental installation:  

Source Code and Snippets

Step 1: After the installation of react-router-dom we can ensure that the package is successfully installed or not by checking the package.json file to see the installed react-router-dom module and its version.

{ 
   "name" : "reactApp", 
   "version" : "1.0.0" 
   "description" : "It is.a react app" 
  "dependencies" : { 
        "react" : "^17.0.2", 
       "react-dom" : "^17.0.2", 
       "react-icons" : "^4.3.1", 
       "react-router" : "^6.2.1", 
       "react-router-dom" : "^6.2.1" 
}, 

Step 2: Then you go straight to your index.js main page to activate BrowserRouter throughout the application running in the App.js file.

import {StrictMode } from "react"; 
import ReactDOM from "react-router-dom" 
import App from "./App" 
import {BrowserRouter} from "react-router-dom" 
const rootElement = document.getElementById("root") 
ReactDOM.render( 
<StrictMode> 
    <BrowserRouter> 
      <App /> 
   </BrowserRouter> 
</StrictMode>, 
  rootElement 
);

Step 3: Now, we can make directories for the components or the pages we want to render. Either you can make separate folders or can have one folder with all components. Using a terminal or with a new tab, folders can be created with ease.

mkdir src/components/Home 
mkdir src/components/About 

Now we will create a component inside each directory we created above. Here we will first create a Home.js file for the Home directory. 

nano src/components/Home/Home.js  

Then add the basic component rendering code for it.

function Home() { 
    return ( 
       <div> 
            <h1> This is the home page </h1> 
      </div> 
    ); 
} 
export default Home; 

Followed by creating an About.js file for the About directory.

nano src/components/About/About.js  

Then add the basic component rendering code for it.  

function About() { 
    return ( 
       <div> 
            <h1> This is the about page </h1> 
      </div> 
    ); 
} 
export default About; 

Step 4: Now come to the main App.js file which is the core of implementing all we have defined and declared till now by defining routes for each component and where and which component they will render when the path matches with the base URL entered or clicked by the user. 

import {Routes , Route } from "react-router-dom" 
import Home from "./components/Home/Home" 
import About from "./components/About/About" 
function App(){ 
   return ( 
      <div className="App"> 
        <Routes> 
            <Route path="/" component={<Home/> } /> 
            <Route path="/about" component={<About/> } /> 
       </Routes> 
    </div> 
)} 
export default App 

This is how we install and set up the basic boilerplate using React Router. After that, it can be extended with its components navigating with respect to website requirements.

Learn advanced routing techniques in ReactJS with upGrad’s React.js For Beginners, designed to strengthen your foundational knowledge. The 14-hour program covers routing principles, component integration, and dynamic navigation.

To understand routing in ReactJS, let’s explore the challenges and effective debugging strategies for seamless navigation.

React Router: Challenges and Debugging

React Router is simple to use if you follow and understand its basic template.

The challenges involved when you installed it on the terminal and tried to activate BrowserRouter but then also routing did not happen. Debugging comes with hands-on practice when you code the concept you visualize with the understanding of the concept learned here.

Have <Link> component  inside <BrowserRouter> component because let's say if you have Header.js component with code :

import React from 'react'; 
import { Link } from 'react-router-dom';  
const Header = () => { 
    return ( 
        <div className="App"> 
             <Link to="/" >  Home  </Link> 
             <Link to="/" >  HomePage </Link> 
        </div> 
    ); 
}; 

and App.js with the rendering looks like : 

import React from 'react'; 
import { BrowserRouter, Route, Link } from 'react-router-dom' 
import Home from "./components/Home/Home" 
import About from "./components/About/About" 
import Header from './Header'; 
const App = () => { 
  return ( 
    <div > 
      <Header /> 
      <BrowserRouter> 
        <div> 
        <Route path="/" exact component={Home} /> 
        <Route path="/about" exact component={About} /> 
        </div>  
      </BrowserRouter> 
    </div> 
  ); 
}; 
export default App;

Here Header.js is using the <Link> component in the Header.js file but <Header> is placed outside <BrowserRouter> in app.js file making the error displayed: “component that is not the child of <Router> cannot contain its components as well.  

Route is the child component of Routes, it must be used like taking Routes as parent component. Here the problem lies in the react-router version installation, react router 6 version does not allow Route to render without wrapping it up in Routes parent component  just like:

function App() { 
    return ( 
      <div> 
      <Routes> 
        <Route path="/Contact" element={<Contact />} /> 
       <Route path="/shop" element={<Shop/>} /> 
      </Routes> 
   </div> 
  ); 
 }  

Do not use anchor tags instead of <Link> components because using anchor tags would not allow applications to remain Single Page Application ( SPA). HTML anchor tag would trigger a page reload or page refresh when clicked. 

Use the default Route always at the end while using switch components. Default Route is in the form of Redirect or Navigate in react router-dom@6 version. 

Redirection happens when a login button is clicked on the Profile page redirecting you to <Login> component. Now <Redirect> is deprecated and {useNavigate} is currently in use with react-router latest version. 

import React from "react" 
import {useNavigate} from "react-router-dom" 
  
export default function Profile() { 
   let navigate = useNavigate() 
   return ( 
   <div> 
         <h2> This is profile </h2> 
         <button> onClick ={()=>{ navigate("/about")}}> Login 
         </button> 
   </div> 
);  

Routes are used rather than switches in react-router-dom@6 install 

<BrowserRouter> 
    <Routes> 
      <Route path="/" element={<Component />}> 
      </Route> 
    </Routes> 
  </BrowserRouter>  

exact keyword must be used to match the component's route paths precisely. If we have code somewhere like this:

<BrowserRouter> 
            <Switch> 
                <Route path="/" component={Home} /> 
                <Route path="/home" component={Main} /> 
            </Switch> 
</BrowserRouter> 

The problem lies here with the Home Route which is the base route. React is needed to tell other routes are also appending with the “/” using exact.

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

Enhance your problem-solving skills by learning data structures and algorithms with upGrad’s Data Structures & Algorithms. This 50-hour program provides expertise in algorithmic strategies, optimization techniques, and practical applications.

Also read: Top 20 Real-Time React Projects and Ideas for Beginners in 2025

Let’s explore the different types of routers in React Router and understand their unique use cases and functionalities.

Different Types of Routers in React Router

React Routers gives us 3 types of routing in reactJS- 

1. Browser Router

The Browser Router is the most commonly used router in ReactJS, leveraging the HTML5 history API (pushState, replaceState, and popstate) to synchronize your UI with the URL. It allows for clean, SEO-friendly URLs and full browser history support, making it ideal for production environments where you need deep linking and the ability to bookmark or refresh pages without losing state.

Use Case: Best for single-page applications (SPAs) with clean URLs and SEO needs.

2. Hash Router

The Hash Router uses the URL’s hash fragment (the part after #) for navigation, avoiding the need for HTML5 history API support. While it doesn’t produce clean URLs like the Browser Router, it works well in environments where you can’t configure server-side routing, such as static file hosting or legacy systems.

Use Case: Useful for static sites or when server-side routing isn’t available.

3. Memory Router

The Memory Router keeps navigation history in memory without affecting the URL. This router is useful in non-browser environments, like React Native or during testing, where the URL doesn’t need to be updated but you still require routing behavior.

Use Case: Ideal for React Native apps, testing, or environments where URL updates are unnecessary.

Enhance your ReactJS skills and learn routing techniques with upGrad’s Generative AI for Software Development course. This program will enhance your understanding of dynamic routing and advanced concepts in modern web development.

To understand the distinction between React Router and React Router DOM, let’s explore their roles and functionality in web development.

What is the Difference Between React Router and React Router DOM?

These two seem identical. react-router is the core npm package for routing, but react-router-dom is the superset of react-router providing additional components like BrowserRouter, NavLink and other components, it helps in routing for web applications.

Here's a table that highlights the differences between react-router and react-router-dom:

Feature

react-router

react-router-dom

Core Library It is the core library for routing in React. It is a superset of react-router for web apps.
Purpose Provides basic routing functionality. Provides additional components and hooks for DOM-specific routing.
Components Does not include DOM-specific components. Includes BrowserRouter, NavLink, Link, and others for web navigation.
Platform Works for all React-based platforms (e.g., React Native). Specifically designed for web applications.
Main Use Case Suitable for routing in non-web environments (e.g., mobile apps). Used in web applications to handle client-side routing.
Installation npm install react-router npm install react-router-dom

Also Read: React JS Architecture Explained: Explore Step-by-Step Implementation and Key Tools

Enhance Your Programming Skills with upGrad!

Routing in ReactJS is a crucial tool for any React developer seeking to create dynamic, single-page applications with seamless navigation. By implementing routing effectively, developers can enhance the user experience without requiring page reloads, thereby improving both performance and usability. 

However, as React applications grow in complexity, learning advanced routing techniques can be a challenge. This is where upGrad’s online software development courses come in. With hands-on experience and expert guidance, upGrad offers the tools to overcome these challenges and become a proficient React developer.

In addition to the courses mentioned above, here are some free courses that can further strengthen your foundation in software engineering.

Feeling uncertain about where to go next in your software development path? Consider availing upGrad’s personalized career counseling. They can guide you in choosing the best path tailored to your goals. You can also visit your nearest upGrad center and start hands-on training today!

Boost your career with our popular Software Engineering courses, offering hands-on training and expert guidance to turn you into a skilled software developer.

Master in-demand Software Development skills like coding, system design, DevOps, and agile methodologies to excel in today’s competitive tech industry.

Stay informed with our widely-read Software Development articles, covering everything from coding techniques to the latest advancements in software engineering.

Reference :
https://expertbeacon.com/a-statistical-analysis-of-react-angular-and-vue-in-2023/

Frequently Asked Questions (FAQs)

1. Which Router is best for React JS?

2. Do we need a React Router with the next JS?

3. What is the difference between a router and a switch?

4. How do I enable routing in React?

5. How does React Router improve user experience in React apps?

6. How do you handle nested routes in React Router?

7. What is the difference between Link and NavLink in React Router?

8. How do you implement route protection in React applications?

9. How does React Router handle query parameters?

10. What is the role of exact keyword in React Router?

11. How does the useParams hook work in React Router?

Pavan Vadapalli

900 articles published

Director of Engineering @ upGrad. Motivated to leverage technology to solve problems. Seasoned leader for startups and fast moving orgs. Working on solving problems of scale and long term technology s...

Get Free Consultation

+91

By submitting, I accept the T&C and
Privacy Policy

India’s #1 Tech University

Executive PG Certification in AI-Powered Full Stack Development

77%

seats filled

View Program

Top Resources

Recommended Programs

upGrad

AWS | upGrad KnowledgeHut

AWS Certified Solutions Architect - Associate Training (SAA-C03)

69 Cloud Lab Simulations

Certification

32-Hr Training by Dustin Brimberry

upGrad KnowledgeHut

upGrad KnowledgeHut

Angular Training

Hone Skills with Live Projects

Certification

13+ Hrs Instructor-Led Sessions

upGrad

upGrad

AI-Driven Full-Stack Development

Job-Linked Program

Bootcamp

36 Weeks