0
0
ReactHow-ToBeginner · 4 min read

How to Create Routes in React Using React Router

To create routes in React, use the react-router-dom library by defining Routes and Route components inside your app. Each Route specifies a path and the component to render when the URL matches that path.
📐

Syntax

Use BrowserRouter to wrap your app for routing support. Inside it, use Routes to group your routes. Each Route has a path attribute for the URL and an element attribute for the component to show.

  • BrowserRouter: Enables routing in the browser.
  • Routes: Container for all route definitions.
  • Route: Defines a single route with path and element.
jsx
import { BrowserRouter, Routes, Route } from 'react-router-dom';

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

Example

This example shows a simple React app with two routes: Home and About. When you visit '/' you see the Home component, and when you visit '/about' you see 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>;
}

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>
  );
}

export default App;
Output
When running, the app shows navigation links 'Home | About'. Clicking 'Home' displays 'Home Page'. Clicking 'About' displays 'About Page'.
⚠️

Common Pitfalls

  • Not wrapping your app in BrowserRouter causes routing to fail.
  • Using component instead of element in Route is outdated in React Router v6.
  • Forgetting to import Routes and Route leads to errors.
  • Using relative paths incorrectly can cause unexpected routing behavior.
jsx
/* Wrong way (React Router v6): */
<Route path="/" component={Home} />

/* Right way: */
<Route path="/" element={<Home />} />
📊

Quick Reference

Remember these key points when creating routes in React:

  • Wrap your app with BrowserRouter.
  • Use Routes to group Route components.
  • Each Route uses path and element props.
  • Use Link for navigation instead of anchor tags.

Key Takeaways

Wrap your React app in BrowserRouter to enable routing.
Define routes inside Routes using Route with path and element props.
Use Link components for navigation to avoid full page reloads.
React Router v6 uses element instead of the older component prop.
Always import routing components from react-router-dom.