1. Home
ReactJS

ReactJS Tutorial: A Comprehensive Guide

Master ReactJS with our in-depth tutorials. From beginner to advanced topics, explore essential concepts and build dynamic web applications effortlessly.

  • 10
  • 3
right-top-arrow
2

React Router DOM

Updated on 02/09/2024499 Views

Introduction to React Router DOM

The React Router DOM is a popular routing library for React applications. The DOM library is an efficient tool for handling client-side routing, organized application structure, nested routing, integration with React ecosystems, dynamic routing, and history management.

Overview

React Router DOM handles both client-side and dynamic routing. It handles client-side routing by how React Router DOM enhances Single Page Applications (SPAs). It also handles dynamic routing because it often contains content that changes depending on user interactions or data fetched from a server.

You can read this post to get an insight into the basic concept of react routing DOM. Get to understand concepts like routers, links, and navigation. 

Setting Up React Router DOM

There are some prerequisites that you must check off your list before you utilize the library. You are required to have the following before getting started with the Router DOM. 

  • Node.js and npm (Node Package Manager)
  • A React Project
  • Package.json File

The section below offers a step-by-step guide for setting up the React ecosystem. 

React Router DOM install

Follow the prompts below to start the React Router DOM installation process. 

  1. Install Node.js and npm (Node Package Manager) by visiting the Node.js official website and selecting your preferred installation packages. 
  2. The next step is opening a terminal or command prompt and navigating to the directory of your React project where you want to install React Router DOM.
  3. You can initialize the project if you don’t have a package.json file by running the following code: npm init -y. The code creates a package.json file with default values.
  4. The next task on the list is installing React Router DOM. You can do that by running the following code to install React Router DOM and add it to your project's dependencies: npm install react-router-dom
  5. The last step is to verify the success of your installation by checking the package.json file or running the npm list react-router-dom code. You should see react-router-dom as the output to signify a successful installation.
  6. You can start using React Router DOM by importing the components and functions from react-router-dom into your application files. Begin implementing client-side routing and navigation according to your preferences. 

Basic Setup in a React Application

Setting up React Router DOM in a React application involves a few steps, and below are highlights of the process. 

  1. Start by creating a React application using the Create React App, a popular tool for setting up React projects. Run the following code and replace the my-app with the preferred name of your project: 

npx create-react-app my-app

cd my-app

  1. Your next move is to define routes in your App. Open the src/App.js file (or any component file where you want to define routes) before setting up your routes using React Router DOM components. Below is an example of JSX code to define routes in your App.

import React from 'react';

import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';

import Home from './components/Home';

import About from './components/About';

import Contact from './components/Contact';

function App() {

return (

<Router>

<div>

<Switch>

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

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

<Route path="/contact" component={Contact} />

</Switch>

</div>

</Router>

);

}

export default App;

  1. You can now create a separate component for each route (e.g., Home.js, About.js, Contact.js) inside the src/components directory or wherever you prefer.
  2. Define components inside each component file by defining the content for the respective route. For example, Home.js:

import React from 'react';

const Home = () => {

return (

<div>

<h1>Home Page</h1>

<p>Welcome to the Home Page!</p>

</div>

);

};

export default Home;

You can repeat the same process for the About and Contact components.

  1. You can run your React application after setting up your routes and creating your components.

  npm start. 

  1. The bash script will start the development server and you can view your React application with React Router DOM routing enabled in your web browser. 

Configuration in index.js or App.js

Configuring React Router DOM in the index.js or App.js file is essential for setting up routing in your React application. Follow the steps below to embark on the configuration process. 

  1. Inside index.js: The code below serves as the entry point of your React application.

import React from 'react';

import ReactDOM from 'react-dom';

import './index.css';

import App from './App';

import { BrowserRouter } from 'react-router-dom'; // Import BrowserRouter

ReactDOM.render(

<BrowserRouter> {/* Wrap your App component with BrowserRouter */}

<App />

</BrowserRouter>,

document.getElementById('root')

);

  1. Inside App.js: You can also configure routing directly with your App.js file using the code below: 
  2. You enable the functionality throughout your React application by configuring React Router DOM using index.js or Apps.js. It allows users to navigate between different views/components based on the URL.

Core Components

React Router DOM contains core components like the <BrowserRouter>, <Routes>, <Route>, <Link>, and <Outlet> components. Below is a highlight of the various Router DOM components. 

  • <BrowseRouters>

The <BrowseRouter> component is an essential wrapper for your application. It utilizes HTML5 history API to keep your UI in sync with the URL. Below is a sample code for the <BrowseRouters> component. 

import { BrowserRouter } from 'react-router-dom';

ReactDOM.render(

<BrowserRouter>

<App />

</BrowserRouter>,

document.getElementById('root')

);

  • <Routes>

The <Routes> component is essential for defining application routes. It replaces the <Switch> component from previous versions of React Router. It renders the first <Route> or <Redirect> that matches the current URL. Below is an illustration of how you can use the Router DOM component. 

import { Routes, Route } from 'react-router-dom';

function App() {

return (

<Routes>

<Route path="/" element={<Home />} />

<Route path="/about" element={<About />} />

<Route path="/contact" element={<Contact />} />

</Routes>

);

}

  • <Route>

The <Route> component renders the UI based on the URL path. Below is a sample code of the <Route> component. 

import { Route } from 'react-router-dom';

<Route path="/about" element={<About />} />

<Route path="/products/:id" element={<ProductDetail />} />

  • <Link>

You can use the <Link> component to navigate between different views in your application without a full page reload. Below is an example of how to use the component. 

import { Link } from 'react-router-dom';

<Link to="/about">About Us</Link>

<Link to={`/products/${productId}`}>Product Details</Link>

  • <Outlet>

The <Outlet> component is essential for rendering child routes within their parent route's component. Below is an example of the <Outlet> component. 

import { Outlet } from 'react-router-dom';

function Products() {

return (

<div>

<h1>Products</h1>

<Outlet /> {/* Renders child routes */}

</div>

);

}

Advanced Routing Concepts 

Advanced routing concepts extend beyond the basic concepts, and you can expect to utilize concepts such as dynamic routing, nested routes, and programmatic navigation. The section highlights the three common advanced routing concepts. 

Dynamic Routing

Dynamic routing involves using path parameters to create routes that respond dynamically to changes in the URL. The useParams hook is a powerful tool for accessing and extracting parameters from the URL within their components, enabling dynamic rendering and data fetching based on the URL parameters. 

Below is an example of how to use the useParams hook in dynamic routing. 

import React from 'react';

import { BrowserRouter as Router, Routes, Route, Link, useParams } from 'react-router-dom';

// Define components for different pages

const Home = () => <h1>Home Page</h1>;

const About = () => <h1>About Page</h1>;

const Contact = () => <h1>Contact Page</h1>;

// UserProfile component using useParams hook to access username parameter

const UserProfile = () => {

const { username } = useParams();

return <h1>User Profile: {username}</h1>;

};

const App = () => {

return (

<Router>

<nav>

{/* Navigation links */}

<ul>

<li><Link to="/">Home</Link></li>

<li><Link to="/about">About</Link></li>

<li><Link to="/contact">Contact</Link></li>

<li><Link to="/profile/johndoe">User Profile (John Doe)</Link></li>

<li><Link to="/profile/janesmith">User Profile (Jane Smith)</Link></li>

</ul>

</nav>

{/* Define routes */}

<Routes>

<Route path="/" element={<Home />} />

<Route path="/about" element={<About />} />

<Route path="/contact" element={<Contact />} />

{/* Dynamic route for user profiles */}

<Route path="/profile/:username" element={<UserProfile />} />

</Routes>

</Router>

);

}

export default App;

Nested Routes

They help organize routing configuration into smaller, more manageable pieces. Below is a practical example of how to use the nested routes component. 

Apps.js

// App.js

import React from 'react';

import { BrowserRouter as Router, Routes, Route, Link } from 'react-router-dom';

import Home from './Home';

import About from './About';

import Contact from './Contact';

const App = () => {

return (

<Router>

<div>

<nav>

<ul>

<li><Link to="/">Home</Link></li>

<li><Link to="/about">About</Link></li>

<li><Link to="/contact">Contact</Link></li>

</ul>

</nav>

<Routes>

<Route path="/" element={<Home />} />

<Route path="/about" element={<About />} />

<Route path="/contact" element={<Contact />} />

</Routes>

</div>

</Router>

);
}

export default App;

Home.js

// Home.js

import React from 'react';

const Home = () => {

return (

<div>

<h1>Home Page</h1>

<p>Welcome to the Home Page!</p>

</div>

);

}

export default Home;

About.js

// About.js

import React from 'react';

const About = () => {

return (

<div>

<h1>About Page</h1>

<p>This is the About Page.</p>

</div>

);

}

export default About;

Contact.js

// Contact.js

import React from 'react';

const Contact = () => {

return (

<div>

<h1>Contact Page</h1>

<p>Contact us at example@example.com.</p>

</div>

);

}

export default Contact;

Programmatic Navigation

You can use the UseHistory / UseNavigate hooks to redirect users programmatically, as shown below. 

import React from 'react';

import { BrowserRouter as Router, Routes, Route, Link, useHistory, useNavigate } from 'react-router-dom';

const Home = () => {

const history = useHistory();

const handleClick = () => {

// Redirect to the About page programmatically

history.push('/about');

};

return (

<div>

<h1>Home Page</h1>

<button onClick={handleClick}>Go to About</button>

</div>

);

}

const About = () => {

const navigate = useNavigate();

const handleClick = () => {

// Redirect to the Home page programmatically

navigate('/');

};

return (

<div>

<h1>About Page</h1>

<button onClick={handleClick}>Go to Home</button>

</div>

);

}

const App = () => {

return (

<Router>

<div>

<nav>

<ul>

<li><Link to="/">Home</Link></li>

<li><Link to="/about">About</Link></li>

</ul>

</nav>

<Routes>

<Route path="/" element={<Home />} />

<Route path="/about" element={<About />} />

</Routes>

</div>

</Router>

);

}

export default App;

Authentication and Protected Routes

This subsection highlights the concepts of protected routes, implementing authentication flow, and use of higher-order components (HOCs) or context API for protecting routes. 

Concept of Protected Routes

The concept of protected routes in React Routing DOM involves configuring routes that are accessible only to authenticated users. You can achieve this by wrapping them in a higher-order component or using conditional rendering based on the user's authentication status.  

Concept of Implementing Authentication Flow 

This concept involves setting up routes for login, registration, and protected content, integrating authentication logic to manage user sessions or tokens. It also involves employing higher-order components or custom hooks to control access to protected routes based on the user's authentication status, thus redirecting unauthorized users to a login page.  

Performance Optimization

Optimizing performance involves practicing concepts such as code splitting with React.lazy and Suspense, efficient route rendering, and avoiding unnecessary renders in your code. 

Common Patterns and Practices

Common patterns and practices in React Router DOM include:

  • Handling 404 Pages - You can configure a custom fallback 404 page to handle navigation to undefined routes, enhancing user experience by gracefully handling navigation errors.
  • Breadcrumbs and Dynamic Links - You can enhance the navigation and provide context within applications using breadcrumbs and dynamic links. 
  • SEO Considerations with React Router - React Router for client-side routing in a web application requires you to factor in server-side rendering (SSR), pre-rendering and static site generation (SSG), <meta> tags, structured data markup, sitemap, canonical URLs, and link building, to help search engines effectively crawl and index your content.

Wrapping Up!

In a rejoinder, the latest React Router DOM offers a robust client-side routing solution for applications. You can leverage its potential to build scalable and SEO-friendly applications that deliver a seamless user experience across different views and interactions.

Frequently Asked Questions (FAQs) 

  1. What is a React Router DOM?

    It is a robust library for declarative routing in React applications, facilitating navigation and managing UI state with dynamic routes.
  1. Is React Router DOM 6 stable?

    Yes, v6 of React Router DOM is stable and safe to use without worrying about migration. 
  1. Is React Router DOM native?

    Unfortunately, React Router DOM is not native React because it is a third-party library. 
  1. Which Router is best for React?

    The choice of the best Router is subjective because it depends on factors such as project requirements, complexity, and personal preference. However, React Router DOM is among the most popular router for React applications. 
  2. What is the difference between React and React DOM?

    React is the core  React library responsible for defining and creating React components, managing component states, and rendering components to the Virtual DOM. React Router DOM is a third-party React library for specific methods for rendering React components into the browser DOM. 
Rohan Vats

Rohan Vats

Passionate about building large scale web apps with delightful experiences. In pursuit of transforming engineers into leaders.

Talk to Career Expert
form image
+91
*
By clicking, I accept theT&Cand
Privacy Policy
image
Join 10M+ Learners & Transform Your Career
Learn on a personalised AI-powered platform that offers best-in-class content, live sessions & mentorship from leading industry experts.
right-top-arrowleft-top-arrow

upGrad Learner Support

Talk to our experts. We’re available 24/7.

text

Indian Nationals

1800 210 2020

text

Foreign Nationals

+918045604032

Disclaimer

upGrad does not grant credit; credits are granted, accepted or transferred at the sole discretion of the relevant educational institution offering the diploma or degree. We advise you to enquire further regarding the suitability of this program for your academic, professional requirements and job prospects before enr...