0
0
ReactHow-ToBeginner · 3 min read

How to Install React Router: Step-by-Step Guide

To install react-router-dom in a React project, run npm install react-router-dom or yarn add react-router-dom. This package provides routing components to manage navigation in React apps.
📐

Syntax

Use the following commands to install React Router in your project:

  • npm: npm install react-router-dom
  • yarn: yarn add react-router-dom

This installs the react-router-dom package, which contains the routing components for React web applications.

bash
npm install react-router-dom
💻

Example

This example shows how to install React Router and use it to create two simple pages with navigation links.

jsx
import React from 'react';
import { BrowserRouter, Routes, Route, Link } from 'react-router-dom';

function Home() {
  return <h2>Home Page</h2>;
}

function About() {
  return <h2>About Page</h2>;
}

export default function App() {
  return (
    <BrowserRouter>
      <nav>
        <Link to="/">Home</Link> | <Link to="/about">About</Link>
      </nav>
      <Routes>
        <Route path="/" element={<Home />} />
        <Route path="/about" element={<About />} />
      </Routes>
    </BrowserRouter>
  );
}
Output
A webpage with navigation links 'Home' and 'About'. Clicking links changes the displayed page heading between 'Home Page' and 'About Page' without reloading.
⚠️

Common Pitfalls

  • Forgetting to install react-router-dom before importing it causes errors.
  • Using react-router instead of react-router-dom for web projects is incorrect; always use react-router-dom.
  • Not wrapping your app in <BrowserRouter> will break routing.
  • Using Switch instead of Routes is legacy; use Routes in React Router v6 and above.
jsx
/* Wrong: Missing BrowserRouter */
import { Routes, Route } from 'react-router-dom';

function App() {
  return (
    <Routes>
      <Route path="/" element={<Home />} />
    </Routes>
  );
}

/* Right: Wrap with BrowserRouter */
import { BrowserRouter, Routes, Route } from 'react-router-dom';

function App() {
  return (
    <BrowserRouter>
      <Routes>
        <Route path="/" element={<Home />} />
      </Routes>
    </BrowserRouter>
  );
}
📊

Quick Reference

Summary tips for installing and using React Router:

  • Run npm install react-router-dom or yarn add react-router-dom to install.
  • Import routing components from react-router-dom.
  • Wrap your app in <BrowserRouter> for web routing.
  • Use <Routes> and <Route> to define routes.
  • Use <Link> for navigation links without page reload.

Key Takeaways

Install React Router with npm or yarn using the command 'npm install react-router-dom'.
Always wrap your React app in to enable routing.
Use and components from react-router-dom v6 for defining routes.
Use components for navigation to avoid full page reloads.
Avoid legacy patterns like and importing from 'react-router' only.