The Wayback Machine - https://web.archive.org/web/20241125194620/https://www.geeksforgeeks.org/reactjs-router/
Open In App

React Router

Last Updated : 17 Oct, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

React Router is a library for handling routing and navigation in React JS Applications. It allows you to create dynamic routes providing a seamless user experience by mapping various URLs to components. It enables navigation in single-page application (SPA) without refreshing the entire page.

This article will walk you through the basics of React Router, its features, the installation process, and how to implement routing in a React application.

React-Router

React Router

What is React Router?

React Router is a standard library for creating dynamic routes and navigation in React JS Applications. It allows you to manage navigation in your app by defining routes that connect the URL paths to specific components.

With React Router, you can implement different views for different parts of your application without the need for a full-page refresh. This is a key feature of single-page applications (SPAs), where only the necessary content is updated as the user navigates.

The current latest verstion is React router dom v6.

Features of React Router

  • Declarative Routing: React Router v6 uses the Routes and Route components to define routes declaratively, making the routing configuration simple and easy to read.
  • Nested Routes: It supports nested routes, allowing for complex and hierarchical routing structures, which helps in organizing the application better.
  • Programmatic Navigation: The useNavigate hook enables programmatic navigation, allowing developers to navigate between routes based on certain conditions or user actions.
  • Route Parameters: It provides dynamic routing with route parameters, enabling the creation of routes that can match multiple URL patterns.
  • Improved TypeScript Support: Enhanced TypeScript support ensures that developers can build type-safe applications, improving development efficiency and reducing errors.

For a detailed exploration of routing in React, check out the guide on ReactJS Course. This resource offers valuable insights into setting up React Router, defining routes, and utilizing components like <Route>, <Switch>, and <Link>. These components make it easy to implement navigation within your application, ensuring that users can move effortlessly from one view to another.

Components of React Router

React Router mainly comprises of the below components

1. BrowserRouter and HashRouter

  • BrowserRouter: Uses the HTML5 history API to keep your UI in sync with the URL.
  • HashRouter: Uses the hash portion of the URL (i.e., window.location.hash) to keep your UI in sync with the URL.
<BrowserRouter>
    (/* Your routes go here */}
</BrowserRouter>

2. Routes and Route

  • Routes: A container for all your route definitions.
  • Route: Defines a single route with a path and the component to render.
<Routes>
    <Route path="/" element={<Home />} />
    <Route path="/about" element={<About />} />
</Routes>
  • Link: Creates navigational links in your application.
  • NavLink: Similar to Link but provides additional styling attributes when the link is active.
<nav>
    <NavLink to="/" activeClassName="active">Home</NavLink>
    <Link to="/about">About</Link>
</nav>

Steps to Create Routes using React Router

Step 1: Initialize React Project

Create React application using the following command.

npx create-react-app react-router-example
cd react-router-example

Step 2: Install React Router

Install react-router in your application write the following command in your terminal

npm install react-router-dom@6

Project Structure

wqerth

Folder Structure

Depenedencies list after installing react router

"dependencies": {
    "@testing-library/jest-dom": "^5.17.0",
    "@testing-library/react": "^13.4.0",
    "@testing-library/user-event": "^13.5.0",
    "react": "^18.3.1",
    "react-dom": "^18.3.1",
    "react-router-dom": "^6.24.1",
    "react-scripts": "5.0.1",
    "web-vitals": "^2.1.4"
}

Example: This example demonstrates implemeting basic routes in a React App.

CSS
/* src/index.css */

body {
    font-family: Arial, sans-serif;
    background-color: #f4f4f4;
    margin: 0;
    padding: 0;
}

h2 {
    text-align: center;
    color: #333;
}

nav ul {
    display: flex;
    justify-content: center;
    list-style: none;
    padding: 0;
}

nav li {
    margin: 0 10px;
}

nav a {
    text-decoration: none;
    color: #333;
}

button {
    display: block;
    margin: 20px auto;
    padding: 10px 20px;
    background-color: #007BFF;
    color: white;
    border: none;
    border-radius: 5px;
    cursor: pointer;
}

button:hover {
    background-color: #0056b3;
}
JavaScript
// src/index.js

import React from "react";
import ReactDOM from "react-dom/client";
import "./index.css";
import App from "./App";

const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(
    <React.StrictMode>
        <App />
    </React.StrictMode>
);
JavaScript
// src/App.js

import React from "react";
import {
    BrowserRouter as Router,
    Routes,
    Route,
    Link,
    useNavigate,
    Outlet,
} from "react-router-dom";


// Home Page Component
const Home = () => {
    const navigate = useNavigate();

    return (
        <div>
            <h2>Home Page</h2>
            <button onClick={() =>
                 navigate("/contact")}>Go to Contact</button>
        </div>
    );
};

// About Page Component 
const About = () => (
    <div>
        <h2>About Page</h2>
        <nav>
            <ul>
                <li>
                    <Link to="team">Our Team</Link>
                </li>
                <li>
                    <Link to="company">Our Company</Link>
                </li>
            </ul>
        </nav>
        <Outlet />
    </div>
);

// Components for other pages
const Contact = () => <h2>Contact Page</h2>;
const Team = () => <h2>Team Page</h2>;
const Company = () => <h2>Company Page</h2>;

function App() {
    return (
        <Router>
            <nav>
                <ul>
                    <li>
                        <Link to="/">Home</Link>
                    </li>
                    <li>
                        <Link to="/about">About</Link>
                    </li>
                    <li>
                        <Link to="/contact">Contact</Link>
                    </li>
                </ul>
            </nav>
            {/*Implementing Routes for respective Path */}
            <Routes>
                <Route path="/" element={<Home />} />
                <Route path="/about" element={<About />}>
                    <Route path="team" element={<Team />} />
                    <Route path="company" element={<Company />} />
                </Route>
                <Route path="/contact" element={<Contact />} />
            </Routes>
        </Router>
    );
}

export default App;

Step 4: Run the application using the following command.

npm start

Output:

Basic Routing in React

React Router

Uses of React Router

  1. Navigation and Routing: React Router provides a declarative way to navigate between different views or pages in a React application. It allows users to switch between views without refreshing the entire page.
  2. Dynamic Routing: React Router supports dynamic routing, which means routes can change based on the application’s state or data, making it possible to handle complex navigation scenarios.
  3. URL Management: React Router helps manage the URLs in your application, allowing for deep linking, bookmarkable URLs, and maintaining the browser’s history stack.
  4. Component-Based Approach: Routing is handled through components, making it easy to compose routes and navigation in a modular and reusable way.

React Router – FAQ’s

How do you install React Router?

To install react router use this npm commang: npm install react-router-dom.

What is the difference between BrowserRouter and HashRouter?

BrowserRouter uses the HTML5 history API, while HashRouter uses the URL hash.

How to pass parameters in React Router?

Use URL parameters in the route path, e.g., path=”/user/:id”.

How do you navigate programmatically?

Use the useNavigate hook or history.push().

Link is a component for navigating without full page reloads.

NavLink is similar to Link but provides active link styling.

How to handle redirects in React Router?

Use the Navigate component within Routes.

How to create nested routes?

Use nested <Route> components within a parent <Route> in Routes.

What is useParams in React Router?

useParams is a hook that returns route parameters from the URL.



Previous Article
Next Article

Similar Reads

React Router vs. React Router DOM
Routing is a fundamental part of any web application. It allows users to move between pages or views. smoothly in traditional web development Routing involves mapping URLs to specific content or views on the server. These are the following topics that we are going to discuss: Table of Content What is a React Router?What is React Router DOM?Differen
4 min read
How to Create Custom Router with the help of React Router ?
To create a custom Router using React Router, you can define a new component that utilizes the Router's 'BrowserRouter' along with 'Route' components to handle different paths and render corresponding components. Use 'Link' components for navigation within your application, providing a seamless routing experience in your React application. What is
3 min read
How does React Router handle navigation in a React application?
React Router is a standard library for routing in React. It enables the navigation among views of various components in a React Application, allows changing the browser URL, and keeps the UI in sync with the URL. Let us create a simple application to React to understand how the React Router works React Router simplifies navigation in React applicat
3 min read
Implementing React Router with Redux in React
This article explores implementing React Router with Redux for enhanced state management and routing in React applications. Table of Content What is React Router and Redux?Approach to implement React Router in ReduxSteps to Setup the React AppWhat is React Router and Redux?React Router facilitates routing in React apps, managing component rendering
3 min read
What are the React Router hooks in React v5?
React Router hooks perform client-side single-page routing that provides a functional and streamlined approach to managing navigation in React applications. It provides a way to directly access the state of the router from functional components, this simplifies tasks like retrieving information about the desired URL and navigating through web pages
5 min read
Implement Nested Routes in React.js - React Router DOM V6
Nested routes in React JS provide hierarchical navigation which is implemented using the outlet component in React Router Dom. Routing in React not only provides routing for the pages but also for rendering multiple components inside that page. Nested routes implement this by defining Routes for Child components inside parent route components. Prer
4 min read
Why switch keyword used in React Router v4 ?
ReactJS is a javascript library that is used to build single-page applications (SPA). React by default does not provide the routing features. We can implement routing in ReactJS projects using React Router. React Router is a library that enables navigation among views of various components in a React Application, allows changing the browser URL, an
5 min read
How is React Router is different from conventional routing ?
React Router is a library for routing in React applications. It allows you to create routes and link to them from your components. When a user clicks a link, React Router will determine which route to use and render the corresponding component. Prerequisites:NodeJS or NPMReact JSReact RouterSteps to Create the React Application And Installing Modul
2 min read
Next.js Migrating from React Router
Are you using React Router in your web application and planning to switch to Next.js? Don't worry, the migration process is easy and we've got you covered! This blog post will guide you through the process and help you understand the benefits of doing so. What is Next.js? Next.js is a React-based framework used for building server-side rendered (SS
5 min read
What are the primary components used in React Router?
In React Router, there are several primary components used for implementing routing and navigation within a React application: BrowserRouter: This component provides the routing functionality for web applications using the HTML5 history API. It manages the interaction between the browser's URL and the React application's UI, enabling navigation wit
2 min read
Top React Router Interview Questions
React Router is widely used with React applications to route and navigate between the applications. In this tutorial, we will see the top React Router questions that can be asked in the interview. Let’s discuss some common questions that you should prepare for the interviews. These questions will be helpful in clearing the interviews, especially fo
15+ min read
Create a basic Navbar using React Router v6
React Router recently released version 6, and earlier version 5 of React Router was used. A lot of changes have been made in v6. In this article, we will understand how to create a basic navbar using React Router v6. Approach to Create a Basic Navbar using React Router v6:<Link></Link>: The Link tag works the same way as the anchor tag,
5 min read
How to handle Nested Routes in React Router ?
React Router allows us to create a hierarchical structure where child components can be rendered within parent components, resulting in a seamless navigation flow. In this article, we will see how to handle nested Routes in React Router. Approach to handle Nested RoutesTo implement nested routes in React Router we define the children routes inside
3 min read
Link Component in React Router
React Router is a powerful library in ReactJS that is used to create SPA (single-page applications) seamlessly. One of the components of the React Router is Link. In this article, we will be seeing the working of the Link component, various props, and usage of the Link component within React Router in developing Single Page Applications. Table of C
5 min read
What is RouterProvider in React Router ?
The RouterProvider in React Router is similar to the traffic controller of our React apps. It helps us monitor how users move between pages and objects in a single-page application (SPA). Essentially, it’s the backbone of React Router, handling all the routing magic behind the scenes. Table of Content What is RouterProvider?Key FeaturesCreating a r
5 min read
React Router V5 vs V6
React Router is widely appreciated in React apps for handling routing and navigation. It provides a way to configure routes. Show components based on the current URL. The newest release, React Router v6 introduces changes and improvements compared to the version of React Router v5. This article will explore the differences between React Router v6 a
7 min read
Routes Component in React Router
Routes are an integral part of React Router, facilitating the navigation and rendering of components based on URL patterns. In this article, we'll delve into the concept of routes, understanding their role in React Router, and how to define and manage routes effectively. Table of Content What are Routes ?Why Routes Are Essential ?Defining RoutesMan
4 min read
Route Component in React Router
React Router is a popular library used for managing routing in React applications. At its core lies the Route component, which plays a pivotal role in defining the relationship between URLs and corresponding components. In this article, we'll delve into the intricacies of the Route component, exploring its purpose, syntax, and practical usage. Tabl
5 min read
How to use the useHistory hook in React Router?
React Router is a standard library system built on top of React and used to create routing in the React application using the React Router Package. It enables the navigation between views of various components in a React Application. React Router is useful for Single Page Applications (SPAs). To use usHistory Hook in React Router, you first need to
4 min read
Navigate Component in React Router
The navigate component is among the built-in components shipped in with React router version 6. It is a component similar to the useNavigate hook. Internally it uses useNavigate to redirect the location. The props passed to Navigate are the same as the arguments passed to the function returned by useNavigate. While functional components in React su
4 min read
useLoaderData Hook in React Router
useLoaderData is a hook provided by React Router. React Router is a JavaScript framework that helps to create and handle routing in React applications. This hook helps to fetch the data for the component before it renders, this improves performance and prevents empty states. Data FetchingWithout the useLoaderData hook, we still have a way to fetch
3 min read
What is StaticHandler in React Router
React Router is a popular library in the React ecosystem that enables routing in single-page applications (SPAs). It allows developers to define navigation and rendering rules based on the URL of the application. One of the essential components of React Router is the StaticHandler, which plays a crucial role in handling static routes within your ap
5 min read
Provide an example of using the useParams hook in React Router.
React Router is a popular library for routing in React applications. One of its powerful features is the useParams hook, which allows developers to access parameters from the URL in functional components. In this article, we'll explore the useParams hook in React Router with a practical example. Prerequisites:NPM & Node.jsReact JSreact-router-d
3 min read
Explain StaticRouter in React Router
React Router is a powerful library for handling routing in React applications, allowing developers to create dynamic single-page applications (SPAs) with ease. While the BrowserRouter is commonly used for client-side routing in web applications, there are scenarios where server-side rendering (SSR) or static site generation (SSG) is preferred. This
4 min read
What is ScrollRestoration in React Router
In React Router, scrollRestoration is a feature that helps maintain the scroll position of a webpage when navigating between different routes within a single-page application. When enabled, it ensures that when a user goes back or forward in their browsing history, the page remembers where they were scrolled to previously, rather than resetting to
8 min read
Explain MemoryRouter in concept of React Router
In React applications, routing is a crucial aspect that enables navigation between different components based on the URL. React Router is a popular library used for managing routing in React applications. One of the components provided by React Router is `MemoryRouter`, which offers a unique way to handle routing without manipulating the browser's
4 min read
Migrate to React Router v6
React Router v6 brings significant changes and improvements over its predecessor, offering a more intuitive API and better performance. Migrating to React Router v6 might seem daunting, but with proper guidance, the transition can be smooth and beneficial for your React applications. Enhancements in React Router v6React Router v6 introduces several
3 min read
How to programmatically navigate using React Router ?
React Router provides a way to navigate between different parts of an application when certain events occur, such as button clicks or form submissions. Programmatically navigating allows us to change the URL of an application without a full page reload, enabling a smoother user experience. We will discuss the different approaches to navigating usin
3 min read
NPM React Router Dom
React Router DOM is a powerful routing library for React applications that enables navigation and URL routing. In this article, we'll explore React Router DOM in-depth, covering its installation, basic usage, advanced features, and best practices. What is React Router DOM?React Router DOM is a collection of navigational components for React applica
2 min read
react-router-dom - NPM
react-router-dom is an important library for handling routing in React applications. It allows you to navigate between different components and manage the browser history. This article will cover everything you need to know about react-router-dom, from installation using npm to implementing routes in a React application. Why Use react-router-dom?Si
4 min read
three90RightbarBannerImg