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?

  • 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 Setup The Application

Step 1: Create a React application using the following command

npx create-react-app foldername

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 Structure

The 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.

CSS
/*App.css*/

#root {
    max-width: 1280px;
    margin: 0 auto;
    padding: 2rem;
    text-align: center;
}

.container {
    display: flex;
    flex-direction: column;
    align-items: center;
}
CSS
/* 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;
}
JavaScript
// 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;
JavaScript
// 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">
                w3wiki
            </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;
JavaScript
// AboutPage.js

const AboutPage = () => {
    return (
        <div>
            <h2>About w3wiki</h2>
            <p>
                w3wiki 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/

react-router-dom – NPM



Contact Us