0
0
Reactframework~5 mins

Defining routes in React

Choose your learning style9 modes available
Introduction

Routes help your app show different pages or views when users click links or enter URLs. They make your app feel like a website with many pages.

You want to show a home page and an about page in your app.
You need to switch views without reloading the whole page.
You want users to bookmark or share links to specific parts of your app.
You want to protect some pages so only logged-in users can see them.
Syntax
React
import { BrowserRouter, Routes, Route } from 'react-router-dom';

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

BrowserRouter wraps your app to enable routing.

Routes holds all your route definitions.

Examples
Defines two routes: home page at '/' and contact page at '/contact'.
React
import { BrowserRouter, Routes, Route } from 'react-router-dom';

function App() {
  return (
    <BrowserRouter>
      <Routes>
        <Route path="/" element={<Home />} />
        <Route path="/contact" element={<Contact />} />
      </Routes>
    </BrowserRouter>
  );
}
Route with a dynamic parameter userId to show different profiles.
React
<Route path="/profile/:userId" element={<Profile />} />
Catch-all route to show a 'Not Found' page for unknown URLs.
React
<Route path="*" element={<NotFound />} />
Sample Program

This React app uses routes to switch between Home and About pages. The navigation links let users change pages without reloading. The aria-label helps screen readers understand the menu.

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

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

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

function App() {
  return (
    <BrowserRouter>
      <nav aria-label="Main navigation">
        <ul>
          <li><Link to="/">Home</Link></li>
          <li><Link to="/about">About</Link></li>
        </ul>
      </nav>
      <Routes>
        <Route path="/" element={<Home />} />
        <Route path="/about" element={<About />} />
      </Routes>
    </BrowserRouter>
  );
}

const container = document.getElementById('root');
const root = createRoot(container);
root.render(<App />);
OutputSuccess
Important Notes

Always wrap your routes inside BrowserRouter to enable routing.

Use Link instead of <a> tags to avoid full page reloads.

Route paths are case sensitive by default.

Summary

Routes let your React app show different pages without reloading.

Use BrowserRouter, Routes, and Route to define routes.

Use Link to navigate between routes smoothly.