← Back to Chapters

React Router — Installation & Setup

? React Router — Installation & Setup

⚡ Quick Overview

React Router is the official routing library for React applications. It enables navigation between multiple views in a single-page application without reloading the browser.

? Key Concepts

  • Client-side routing
  • Single Page Application (SPA)
  • createBrowserRouter API
  • RouterProvider wrapper

? Step 1: Install React Router

? View Code Example
// Install React Router for web applications
npm install react-router-dom
? View Code Example
// Yarn alternative installation command
yarn add react-router-dom

?️ Step 2: Project Structure

? View Code Example
// Recommended folder structure for React Router apps
src/
│
├── components/
│   ├── Navbar.js
│   └── Home.js
│
├── pages/
│   ├── About.js
│   └── Contact.js
│
├── App.js
├── router.js
└── index.js

⚙️ Step 3: Configure Router

? View Code Example
// index.js - Define routes using createBrowserRouter
import React from "react";
import ReactDOM from "react-dom/client";
import { createBrowserRouter, RouterProvider } from "react-router-dom";
import App from "./App";
import About from "./pages/About";
import Contact from "./pages/Contact";

const router = createBrowserRouter([
{ path: "/", element: <App /> },
{ path: "/about", element: <About /> },
{ path: "/contact", element: <Contact /> },
]);

ReactDOM.createRoot(document.getElementById("root")).render(
<RouterProvider router={router} />
);

? Step 4: Basic Components

? View Code Example
// App.js - Navigation using Link component
import React from "react";
import { Link } from "react-router-dom";

function App() {
return (
<div className="text-center">
<h2>Welcome to My React Router App</h2>
<nav>
<Link to="/">Home</Link>
<Link to="/about">About</Link>
<Link to="/contact">Contact</Link>
</nav>
</div>
);
}

export default App;

? Live Explanation

Navigation happens instantly without page reloads because React Router intercepts route changes and updates the UI dynamically.

? Tips & Best Practices

  • Always wrap your app with RouterProvider
  • Use Link instead of anchor tags
  • Keep routes simple initially
  • Organize routes using pages folder

? Try It Yourself

  1. Create a new React app
  2. Install react-router-dom
  3. Add Home, About, Contact routes
  4. Verify navigation without reload