View All
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 for Beginners [With Examples]

By Pavan Vadapalli

Updated on May 12, 2025 | 21 min read | 42.38K+ views

Share:

Latest Update:

The recent Router v7.5.x release (v7.5.0 to v7.5.1, April 2025) focuses on better pre-rendering, dependency optimization, and improved error handling, especially when used with modern build tools like Vite.

React Router is integral to modern React development. It enables seamless navigation within single-page applications (SPAs), allowing developers to build dynamic user interfaces without full-page reloads. 

According to recent statistics, React Router is included in 44% of all React projects, highlighting its widespread adoption and importance in the React ecosystem.

In this blog, you’ll gain a comprehensive understanding of React Router, from its basic setup to advanced routing techniques.

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 React Routing in Web Development

React 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. It can still serve as a boilerplate for understanding routing and as 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:

  • Initially, the page will show the "Cart" button.
  • When the user clicks on the "Cart" button, the page will display the Cart component. If the cart array is empty, it will show the message "Your cart is empty."
  • If you add items to the cart array, they will be displayed as a list inside the Cart component.

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

Web development is at the heart of routing, and to master it, one should first understand the basic fundamentals of web development through a comprehensive course, followed by a React.js certification course to kickstart learning React Routing!

Server-side routing results in every request being a full page refresh loading unnecessary and repeated data every time causing a bad UX and delay in loading. 

With client-side routing, it could be the rendering of a new component where routing is handled internally by JavaScript. The component is rendered only without the server being reloaded.

React Router helps us to navigate the components and build a single-page application without page-refresh when the user navigates making it an effective UX experience. 

Basic Routing 

React Router API

Browser Router or React Router API  is a most popular library  for routing in react to navigate among different components in a React Application keeping the UI in alignment with 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

There are 3 different packages for React Routing. 

  • react-router: It is the heart of react-router and provides core functionalities for routing in web applications and all the packages for react-router- dom and react-router-native  
  • react-router-native: It is used for routing in mobile applications  
  • react-router-dom: It is used to implement dynamic routing in web applications.

 

Coverage of AWS, Microsoft Azure and GCP services

Certification8 Months

Job-Linked Program

Bootcamp36 Weeks

Facing challenges with debugging and advanced routing? Improve your skills and tackle complex web development problems with upGrad’s AI-Driven Full Stack Development Bootcamp. Master scalable application development using the latest technologies!

How Routing Works / Routing Mechanism

 

We know routing is user-side navigation to different pages or different pages on a website. Every rendering mechanism has its own routing way to navigate but dealing with React Router here that comes under Client Side Routing but eventually under Client Side Rendering has a dynamic mechanism to look upon. 

Client Side rendering orders the server to deal with data only whereas the rest of all rendering and routing is handled by the client itself.  

Traditional routing has always requested the server to provide different index.html of different pages, but Client Side Rendering will only return one index.html file for Client Side Routing.  

This will give you a smooth Single Page Application Routing experience with forward and backward route ability using history API keeping the URL updated as well.

Installation and the Steps for React Router

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 15 React Developer Tools 2024: Installation and Features

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.

 

Want to dive deeper into React? Enroll in upGrad’s free React JS course to master the fundamental concepts and routing mechanisms in React. Start building dynamic web applications today!

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} />

 

Having trouble with efficient routing and data handling? Strengthen your foundation with upGrad’s data structures and algorithms free course. Get the skills needed to solve complex programming challenges effectively!

How to Use React Router in Typescript

React-Router@5 is generally used for routing generally, but React-Router@6 is great for typescript programmers shipping type definitions. With packages installed react-router with typescript quick starts normally. 

  • npm install react-router-dom 
  • npm install @types/react-router-dom 

Typescript is an extension of JavaScript, adding one good layer of safety and typing into the existing code, typing makes it easy for programmers to trace the problem. 

React Router Examples

React Router can be implemented in any case where the primary requirement is to navigate. Navbars, User Registration and Login can be implemented too. 

The segregation of components into their pages is considered to be react routing best practices. 

Step 1: Activate BrowserRouter in index.js file

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

Step 2: Make different components to render on routing: Home, Wishlist, Cart, No Match. 

import React from "react" 
function Home() { 
    return ( 
       <div> 
            <h1> This is the home page </h1> 
      </div> 
    ); 
} 
export default Home; 
 
import React from "react" 
  
export default function Cart() { 
    return  <h1> This is Cart </h1> 
} 
import React from "react" 
export default function WishList() { 
 return  <h1> This is Wishlist </h1>
} 

 

import React from "react" 
  
export default function NoMatch() { 
    return  <h1> This is  404 </h1> 
} 

Step 3: Route them in app.js file accordingly 

import "./styles.css"; 
import {Routes , Route } from "react-router-dom"; 
import Home from "./pages/Home"; 
import Cart from "./pages/Cart"; 
import WishList from "./pages/WishList"; 
import NoMatch from "./pages/NoMatch"; 
import {Link} from "react-router-dom"; 
  
export default function App() { 
   return ( 
      <div className="App"> 
        <nav> 
            <Link to ="/"> Home </Link> || 
            <Link to ="/cart"> Cart </Link> || 
            <Link to ="/wishlist"> Wishlist </Link>  
       </nav> 
       <Routes> 
          <Route path ="/" element= {<Home />}/> 
          <Route path ="/cart" element= {<Cart />}/> 
          <Route path ="/wishlist" element= {<WishList />}/> 
          <Route path ="*" element= {<NoMatch />}/> 
       </Routes> 
  </div> 
); 
} 

The react router navbar would look like this: 

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.

Components in React Router and their Explanation

React Router DOM in reactJS is categorized into three primary components :  

1. Routers

As we know, react-router-dom is an npm package that helps in dynamic routing, and provides <BrowserRouter> and <HashRouter>. 

A) BrowserRouter: It is one of the parent components that is used to store all <Route> components that basically instruct the react app to navigate the components based on the route requested by the client. It is usually given an alias name ‘Router’ for ease of reference. It allows us to frame a complete and proper URL for navigation. Also, an additional point includes BrowserRouter gives us an inch of pain to handle the different routes configurations on the server-side This matters when you need to deploy large-scale production apps. 

The syntax works like:

<BrowserRouter 
       basename = {{optionalString} 
       forceRefresh={optionalBool} 
       getUserConfirmation={optionalFunc} 
       keyLength = {optionaNumber} 
> 
  <App/> 
</BrowserRouter> 
  • basename: The basename prop is used to provide a base URL path for all the locations in the application. 
  • forceRefresh: It is a Boolean prop when set to true, refreshes and reloads the entire page with any route navigated across the same page.   
  • getUserConfirmation: A function that is used to confirm navigation but by default windows confirm it with window.confirm(). 
  • keyLength: Location is a client-side library that allows us to implement routing, each location has the unique key but by default the key length: 6  

The fundamental react router dom example is as follows:

import "./styles.css" 
import {BrowserRouter} from "react-router-dom" 
import {Routes, Route} from "./pages/Home" 
import ProductDetail from "./pages/ProductDetail" 
export default function App( ) { 
return  
   <BrowserRouter> 
      <div className ="App"/> 
     <Routes> 
         <Route path = "/" element = {<Home />} /> 
         <Route path = "/product-detail" element = {<ProductDetail />} /> 
     </Routes> 
  </div> 
</BrowserRouter> 
) 

HashRouter: It is the same as BrowserRouter but covers the two disadvantages of it when the BrowserRouter is not able to handle some old legacy servers or static servers like GitHub Pages, then HashRouter replaces it. As the name suggests, it first and foremost adds # to the forming base URL, it is used when there is no dependency on server-side configurations. It is just a  # that is added between domain and path, and due to no dependency on history API, it works well in legacy servers. Also as it does not send anything written after # to the server request for say: https:// localhost:3000/#/about, the request will always go to / in the server, making the server happy to handle one single file only and the rest route path is handled at client side only to navigate the client to correct the route instantly.  

2. Route Matchers

They are the matchers to navigate clients to and from the correct URL   requested for using: 

a. Route: It is the most basic component that maps location to different react components to render a specific UI when the path matches the current URL. It is an alternative to an if-statement logic for saying if want to go to the requested /about the path, the route is responsible for rendering that specific component matching across the current URL like <Route path =”/about” component ={ About }/>

<Route path ="/" component={<Home />} /> 
<Route path ="/about" component={<About />} /> 
<Route path ="/blogs" component={<Blogs />}/> 

b. Switch: This component works similarly to the switch statement. It cuts down the exhaustive checking of each route path with the current URL instead the switch once gets the correct route path it returns back from there instead of checking till the last route path is written.    

import {BrowserRouter , Switch, Route } from "react-router-dom" 
<Switch> 
     <Route path ="/" component={<Home />} /> 
     <Route path ="/about" component={<About />} /> 
     <Route path ="/blogs" component={<Blogs />}/> 
</Switch> 

Route Changers: There are three types of navigators or route changes : 

  • Link: It is one of the primary ways to navigate the routes instead of putting it in the address bar you render it on UI as fully accessible just like anchor <href> tags of HTML with the main  difference of anchor tags reload the UI to navigate, but links do not reload it again 
  • NavLink: It is an extended version of Link such that it allows us to see whether the  

< Link > is active or not. This component provides isActive property that can be used with the className attribute. 

3. Redirect

It is a kind of force navigation that will redirect user to the specific page programmers want if such a route is yet not present in the application to navigate forward to. It is a substitute for 404 error pages depending on the website requirement. It exists to have a strong use-case when user signs up on any web-application he is automatically  redirected to the login page making UI experience more efficient.

<Switch> 
      <Link to ="/home"> Home </Link> 
      <NavLink to ="about" className={({ isActive }) => 
(isActive ? 'active': 'inactive')}>About</NavLink> 
      <Route path="/" component={<Home/>} /> 
      <Route path="/about" component = {<About/>} /> 
</Switch>

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: Implementation & Best Practices in 2024

Enhance Your Programming Skills with upGrad!

ReactJS routing empowers developers to build dynamic, multi-page applications by managing navigation between components seamlessly with react-router-dom. By understanding key concepts like Route, Link, and useHistory, beginners can easily implement effective routing and improve the user experience in their React applications.

upGrad offers comprehensive programs that provide hands-on experience with advanced technology and industry experts.

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 Links:
https://ui.dev/react-router-tutorial    
https://reactrouter.com/

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

Microsoft | upGrad KnowledgeHut

Microsoft Azure Data Engineering Certification

Access Digital Learning Library

Certification

45 Hrs Live Expert-Led Training

upGrad

upGrad KnowledgeHut

Professional Certificate Program in UI/UX Design & Design Thinking

#1 Course for UI/UX Designers

Bootcamp

3 Months