Menu

Setting Up React Router

Setting Up React Router

Installation

bash

npm install react-router-dom

Example

src/main.jsx

jsx

import { StrictMode } from "react";
import { createRoot } from "react-dom/client";
import { BrowserRouter } from "react-router-dom";
import App from "./App.jsx";
import "./index.css";

createRoot(document.getElementById("root")).render(
  <StrictMode>
    <BrowserRouter>
      <App />
    </BrowserRouter>
  </StrictMode>
);
src/App.jsx
jsx
import { Routes, Route } from "react-router-dom";
import Navbar from "./components/Navbar";
import Home from "./pages/Home";
import Courses from "./pages/Courses";
import About from "./pages/About";

function App() {
  return (
    <div>
      <Navbar />
      <Routes>
        <Route path="/" element={<Home />} />
        <Route path="/courses" element={<Courses />} />
        <Route path="/about" element={<About />} />
      </Routes>
    </div>
  );
}

export default App;

How It Works

  • <BrowserRouter> wraps the whole app and enables routing. It goes in main.jsx, above everything.
  • <Routes> holds all your route definitions and renders whichever one matches the current URL.
  • <Route path="/courses" element={<Courses />} /> — when the URL is /courses, render the Courses component.
  • <Navbar /> sits outside <Routes>, so it appears on every page.

File Organisation

Full-page components conventionally live in a pages/ folder, separate from reusable components/:

text

src/
├── components/
│   ├── Navbar.jsx
│   └── CourseCard.jsx
├── pages/
│   ├── Home.jsx
│   ├── Courses.jsx
│   └── About.jsx
├── App.jsx
└── main.jsx

ReactJS Tutorial

VA

Vishalini A



Learn via Video Course

React.js for Beginners: Build Modern Web Applications with React Logo

React.js for Beginners: Build Modern Web Applications with React

6 hrs



Get in Touch For Details