0
0
ReactHow-ToBeginner · 4 min read

How to Use Route Component in React for Navigation

In React, use the Route component from react-router-dom to render UI based on the URL path. Wrap your routes inside a Routes component and specify the path and element props on each Route to define which component shows for which URL.
📐

Syntax

The Route component defines a mapping between a URL path and a React component to display. It must be used inside a Routes container. The main props are:

  • path: The URL pattern to match.
  • element: The React element (component) to render when the path matches.

Example syntax:

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

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

Example

This example shows a simple React app with two routes: Home and About. When you visit /, it shows the Home component. When you visit /about, it shows the About component.

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
When visiting '/' URL, the page shows 'Home Page'. When visiting '/about', it shows 'About Page'. Navigation links let you switch between these pages without reloading.
⚠️

Common Pitfalls

Common mistakes when using Route include:

  • Not wrapping Route components inside a Routes container, which causes errors.
  • Using the old component prop instead of element (React Router v6 uses element).
  • Forgetting to use BrowserRouter or another router at the app root.
  • Not using Link for navigation, causing full page reloads.

Wrong way (legacy):

jsx
import { Route } from 'react-router-dom';

// This will cause error in React Router v6
<Route path="/" component={Home} />
📊

Quick Reference

PropDescription
pathURL path to match for this route
elementReact element to render when path matches
indexBoolean to mark this route as the default child route
caseSensitiveBoolean to make path matching case sensitive

Key Takeaways

Always wrap Route components inside a Routes container.
Use the element prop with a React element, not the old component prop.
Wrap your app in BrowserRouter to enable routing.
Use Link components for navigation to avoid full page reloads.
Define clear path props to control which component shows for each URL.