Routing in ReactJS for Beginners [With Examples]
Updated on May 12, 2025 | 21 min read | 42.38K+ views
Share:
For working professionals
For fresh graduates
More
Updated on May 12, 2025 | 21 min read | 42.38K+ views
Share:
Table of Contents
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!
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:
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.
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.”
There are 3 different packages for React Routing.
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.
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:
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.
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} />
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.
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 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:
React Routers gives us 3 types of routing in reactJS-
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.
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.
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.
React Router DOM in reactJS is categorized into three primary components :
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>
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.
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 > is active or not. This component provides isActive property that can be used with the className attribute.
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>
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
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/
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
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
Top Resources