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. Here, we 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?
- Single Page Applications:
react-router-dom
is essential for SPAs where you need to navigate between different views or components without refreshing the entire page. - Dynamic Routing: It allows you to define routes dynamically and manage navigation programmatically.
- URL Management: Provides a way to manipulate the browser's URL, which enhances the user experience and supports deep linking.
Steps to Set Up the Application
Step 1: Create a React application using the following command
npm create vite@latest foldername -- --template react
Step 2: After creating your project folder i.e. foldername, move to it using the following command
cd foldername
Step 3: Next, install react-router-dom using the following command
npm install react-router-dom
Project Structure
Folder StructureThe updated dependencies in package.json file will look like
"dependencies": {
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-router-dom": "^6.23.1"
},
Setting Up react-router-dom
After installing react-router-dom
, you can set up routing in your React application. Here’s a step-by-step guide to get you started:
Import BrowserRouter, Route, and Switch
Open your App.js
file and import the necessary components from react-router-dom
.
import React from 'react';
import { BrowserRouter as Router, Routes,Route } from 'react-router-dom';
Define Routes: Use the Router
, Routes
, and Route
components to define your application’s routes.
function App() {
return (
<Router>
<div>
<Routes>
<Route path="/" element={<Home />} />
<Route path="/about" element={<About />} />
<Route path="/contact" element={<Contact />} />
</Routes>
</div>
</Router>
);
}
const Home = () => <h2>Home Page</h2>;
const About = () => <h2>About Page</h2>;
const Contact = () => <h2>Contact Page</h2>;
export default App;
- Router: Wraps your application and provides routing context.
- Routes: A container for nested
Route
elements. - Route: Defines a mapping between a URL path and a component.
Example
Implementation of react-router-dom where there will be two pages i.e. HomePage and AboutPage.
App.js
/*App.css*/
#root {
max-width: 1280px;
margin: 0 auto;
padding: 2rem;
text-align: center;
}
.container {
display: flex;
flex-direction: column;
align-items: center;
}
Homepage.js
/* HomePage.css */
.homepage-container {
max-width: 800px;
margin: 0 auto;
padding: 20px;
}
.main-heading {
color: green;
text-align: center;
}
.sub-heading {
color: #333;
}
.course-list {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
gap: 20px;
}
.course {
background-color: #f9f9f9;
padding: 20px;
border-radius: 5px;
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}
.course h3 {
margin-top: 0;
}
.course p {
margin-bottom: 0;
}
App.js
// App.js
import {
BrowserRouter as Router,
Routes, Route,
Link
} from 'react-router-dom';
import HomePage from './HomePage';
import AboutPage from './AboutPage';
import './App.css';
const App = () => {
return (
<Router>
<div className="container">
<nav>
<ul>
<li>
<Link to="/">
Home
</Link>
</li>
<li>
<Link to="/about">
About
</Link>
</li>
</ul>
</nav>
<Routes>
<Route path="/"
element={<HomePage />} />
<Route path="/about"
element={<AboutPage />} />
</Routes>
</div>
</Router>
);
};
export default App;
Homepage.js
// HomePage.js
import './HomePage.css';
const Course = ({ title, description }) => {
return (
<div className="course">
<h3>{title}</h3>
<p>{description}</p>
</div>
);
};
const HomePage = () => {
const courses = [
{
title: "Data Structures",
description: `Learn about various data
structures like arrays, linked lists, and trees.`,
},
{
title: "Algorithms",
description: `Explore different algorithms
such as sorting and searching algorithms.`,
},
{
title: "Web Development",
description: `Get started with web development
technologies like HTML, CSS, and JavaScript.`,
},
];
return (
<div className="homepage-container">
<h2 className="main-heading">
GeeksforGeeks
</h2>
<h3 className="sub-heading">
Courses:
</h3>
<div className="course-list">
{courses.map((course, index) => (
<Course key={index}
title={course.title}
description={course.description} />
))}
</div>
</div>
);
};
export default HomePage;
AboutPage.js
// AboutPage.js
const AboutPage = () => {
return (
<div>
<h2>About GeeksforGeeks</h2>
<p>
GeeksforGeeks is a computer
science portal that offers
high-quality content for learning
and practicing various programming
concepts and technologies.
</p>
<p>
Our mission is to provide free
and accessible education to everyone,
empowering individuals to enhance their
skills and pursue careers in technology.
</p>
</div>
);
};
export default AboutPage;
Step to Run Application: Run the application using the following command from the root directory of the project
npm start
Output
Your project will be shown in the URL http://localhost:3000/ (Copy-Paste it in your browser)
react-router-dom - NPM
Similar Reads
Non-linear Components In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
JavaScript Tutorial JavaScript is a programming language used to create dynamic content for websites. It is a lightweight, cross-platform, and single-threaded programming language. It's an interpreted language that executes code line by line, providing more flexibility.JavaScript on Client Side: On the client side, Jav
11 min read
Web Development Web development is the process of creating, building, and maintaining websites and web applications. It involves everything from web design to programming and database management. Web development is generally divided into three core areas: Frontend Development, Backend Development, and Full Stack De
5 min read
Spring Boot Tutorial Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
React Interview Questions and Answers React is an efficient, flexible, and open-source JavaScript library that allows developers to create simple, fast, and scalable web applications. Jordan Walke, a software engineer who was working for Facebook, created React. Developers with a JavaScript background can easily develop web applications
15+ min read
Class Diagram | Unified Modeling Language (UML) A UML class diagram is a visual tool that represents the structure of a system by showing its classes, attributes, methods, and the relationships between them. It helps everyone involved in a projectâlike developers and designersâunderstand how the system is organized and how its components interact
12 min read
Steady State Response In this article, we are going to discuss the steady-state response. We will see what is steady state response in Time domain analysis. We will then discuss some of the standard test signals used in finding the response of a response. We also discuss the first-order response for different signals. We
9 min read
JavaScript Interview Questions and Answers JavaScript (JS) is the most popular lightweight, scripting, and interpreted programming language. JavaScript is well-known as a scripting language for web pages, mobile apps, web servers, and many other platforms. Both front-end and back-end developers need to have a strong command of JavaScript, as
15+ min read
React Tutorial React is a JavaScript Library known for front-end development (or user interface). It is popular due to its component-based architecture, Single Page Applications (SPAs), and Virtual DOM for building web applications that are fast, efficient, and scalable.Applications are built using reusable compon
8 min read
Backpropagation in Neural Network Back Propagation is also known as "Backward Propagation of Errors" is a method used to train neural network . Its goal is to reduce the difference between the modelâs predicted output and the actual output by adjusting the weights and biases in the network.It works iteratively to adjust weights and
9 min read