React Mastery / Routing (React Router)

Basic Routing Setup

🧠 Core Idea of Routing

In React Router:

  • Each URL path is mapped to a React component

  • When the URL changes, React Router renders the matching component

  • No page refresh happens


πŸ”‘ Key Components

<Routes>

  • Acts as a container for all routes

  • React Router checks routes inside it and renders the best match

  • Replaces <Switch> from older versions

<Routes>
  {/* All Route components go here */}
</Routes>

<Route path element />

  • Defines a single route

  • path β†’ URL path

  • element β†’ Component to render

<Route path="/about" element={<About />} />

πŸ“Œ Important:

In v6, element expects JSX, not a component reference.

❌ Wrong

element={About}

βœ… Correct

element={<About />}

🏠 Default Route (/)

  • Represents the home page

  • Loads when the app opens

<Route path="/" element={<Home />} />

❌ 404 Page (Wildcard Route)

  • Matches any route that doesn’t exist

  • Uses as a wildcard

<Route path="*" element={<NotFound />} />

πŸ“Œ Always place this at the bottom of your routes.


πŸ“ Folder Structure (Recommended)

src/
 β”œβ”€ pages/
 β”‚   β”œβ”€ Home.jsx
 β”‚   β”œβ”€ About.jsx
 β”‚   β”œβ”€ Contact.jsx
 β”‚   └─ NotFound.jsx
 β”œβ”€ App.jsx
 └─ main.jsx

πŸ› οΈ Hands-On: Create Basic Pages

src/pages/Home.jsx

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

export default Home;

src/pages/About.jsx

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

export default About;

src/pages/Contact.jsx

function Contact() {
  return <h1>Contact Page</h1>;
}

export default Contact;

src/pages/NotFound.jsx

function NotFound() {
  return <h1>404 - Page Not Found</h1>;
}

export default NotFound;

πŸ”— Define Routes in App.jsx

import { Routes, Route } from 'react-router-dom';
import Home from './pages/Home';
import About from './pages/About';
import Contact from './pages/Contact';
import NotFound from './pages/NotFound';

function App() {
  return (
    <Routes>
      <Route path="/" element={<Home />} />
      <Route path="/about" element={<About />} />
      <Route path="/contact" element={<Contact />} />
      <Route path="*" element={<NotFound />} />
    </Routes>
  );
}

export default App;

βœ… How It Works (Flow)

  1. User enters a URL

  2. React Router checks all <Route> paths

  3. Best match is selected

  4. Corresponding component is rendered


🧠 Common Beginner Mistakes

  • ❌ Forgetting to wrap app with BrowserRouter

  • ❌ Using Switch instead of Routes

  • ❌ Writing element={Component} instead of JSX

  • ❌ Missing route for 404 handling