Popular Searches
Popular Course Categories
Popular Courses

Routes and Route Components

Routes and Route Components

React Router

Routes and Route Components in React

Routes and Route Components are essential concepts in React Router that help developers create multi-page navigation experiences in React applications. The Routes component identifies the best matching route for the current URL, while each Route defines a URL pattern and the React component to display when that pattern matches.

Course: React JS Training | JustAcademy React JS Training


1. What Are Routes and Route Components?

What Is Routes?

Routes is a React Router component that examines the current URL and renders the branch of routes that best matches it. It groups the route definitions for a particular part of your application.

What Is Route?

Route defines a relationship between a URL path and a React element. When the current URL matches the route's path, React Router renders the specified element.

Example

import { Routes, Route } from "react-router";

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

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

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

export default App;

In this example, visiting / displays the Home component, while visiting /about displays the About component.

2. Why Do We Use Routes and Route?

  • Organized navigation: Define different URL paths for different application views.
  • Component rendering: Display the appropriate React component based on the URL.
  • Single-page applications: Support navigation without a full-page reload during normal client-side routing.
  • Nested layouts: Organize pages under shared layouts such as dashboards and admin panels.
  • Dynamic URLs: Support routes containing values such as product IDs and user IDs.
  • Fallback handling: Display a custom page when a URL does not match a defined route.

3. Prerequisites

Before learning Routes and Route Components, you should understand:

  • React components and JSX.
  • JavaScript functions and imports/exports.
  • Basic React application structure.
  • The purpose of BrowserRouter.

Install React Router in your project if it is not already installed:

npm install react-router

The examples in these notes use the current declarative React Router imports from react-router. Existing projects and older tutorials may use a different package import depending on the installed version.

4. Understanding the Basic Route Structure

In a typical declarative React Router setup, the application is wrapped in BrowserRouter, and route definitions are placed inside Routes.

import React from "react";
import ReactDOM from "react-dom/client";
import { BrowserRouter, Routes, Route } from "react-router";

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

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

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

ReactDOM.createRoot(document.getElementById("root")).render(
  <BrowserRouter>
    <App />
  </BrowserRouter>
);

Code Explanation

  • BrowserRouter provides the browser-based routing context.
  • Routes contains the route definitions and selects the best matching branch.
  • Route defines a path and its corresponding element.
  • path specifies the URL pattern.
  • element specifies the React element to render for the matching route.

5. The path and element Props

Two important props used with a basic Route are path and element.

Prop Purpose Example
path Defines the URL pattern to match. path="/services"
element Defines the React element to render when the route matches. element={<Services />}
index Defines a default child route at its parent's URL. index
caseSensitive Controls whether path matching is case-sensitive. caseSensitive

6. Creating Multiple Routes

A React application can define multiple routes for different pages, such as Home, About, Services, and Contact.

import { Routes, Route } from "react-router";

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

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

function Services() {
  return <h2>Our Services</h2>;
}

function Contact() {
  return <h2>Contact Us</h2>;
}

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

export default App;

Each route represents a different view. You can test them by opening the following URLs in your development environment:

  • http://localhost:5173/
  • http://localhost:5173/about
  • http://localhost:5173/services
  • http://localhost:5173/contact

7. Navigating Between Routes with Link

Defining routes makes pages available, but users also need a way to navigate between them. React Router provides the Link component for internal navigation.

import { Link } from "react-router";

function Navigation() {
  return (
    <nav>
      <Link to="/">Home</Link>
      {" | "}
      <Link to="/about">About</Link>
      {" | "}
      <Link to="/services">Services</Link>
      {" | "}
      <Link to="/contact">Contact</Link>
    </nav>
  );
}

export default Navigation;

The to prop specifies the destination URL. When a user clicks a Link, React Router normally updates the URL and renders the matching view without a full-page reload.

8. Using an Index Route

An index route displays the default child component at the URL of its parent route. It is useful for a home page inside a shared layout.

import { Routes, Route, Outlet } from "react-router";

function MainLayout() {
  return (
    <div>
      <h1>My Website</h1>
      <Outlet />
    </div>
  );
}

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

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

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

export default App;

Here, the Home component renders at /, and the About component renders at /about. The Outlet component marks where the selected child route should appear inside the layout.

9. Nested Routes

Nested routes let you organize related pages under a parent route. They are commonly used for dashboards, account settings, admin panels, and product sections.

import { Routes, Route, Outlet } from "react-router";

function DashboardLayout() {
  return (
    <div>
      <h1>Dashboard</h1>
      <Outlet />
    </div>
  );
}

function DashboardHome() {
  return <h2>Dashboard Overview</h2>;
}

function Settings() {
  return <h2>Account Settings</h2>;
}

function App() {
  return (
    <Routes>
      <Route path="/dashboard" element={<DashboardLayout />}>
        <Route index element={<DashboardHome />} />
        <Route path="settings" element={<Settings />} />
      </Route>
    </Routes>
  );
}

export default App;

This configuration creates two URLs:

  • /dashboard displays the Dashboard Overview inside DashboardLayout.
  • /dashboard/settings displays Account Settings inside DashboardLayout.

Important: Child routes render through the parent's Outlet. Without an Outlet, the parent layout may appear without the child route content.

10. Dynamic Routes

Dynamic routes use a URL parameter when the path contains a value that can change, such as a user ID, product ID, or article slug. Dynamic segments begin with a colon.

import { Routes, Route, useParams } from "react-router";

function ProductDetails() {
  const { productId } = useParams();

  return <h2>Product ID: {productId}</h2>;
}

function App() {
  return (
    <Routes>
      <Route
        path="/products/:productId"
        element={<ProductDetails />}
      />
    </Routes>
  );
}

export default App;

For a URL such as /products/101, the productId parameter will be "101".

11. Creating a 404 Not Found Route

A fallback route helps display a friendly message when the current URL does not match any other defined route. The wildcard path * is commonly used for this purpose.

import { Routes, Route } from "react-router";

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

function NotFound() {
  return (
    <div>
      <h1>404 - Page Not Found</h1>
      <p>The page you are looking for does not exist.</p>
    </div>
  );
}

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

export default App;

If a user opens an undefined path, such as /unknown-page, the NotFound component is rendered.

12. Routes vs. Route

Feature Routes Route
Purpose Groups route definitions and selects the best matching branch. Defines an individual route pattern and its element.
Usage Contains Route components. Normally used inside Routes in declarative routing.
URL matching Evaluates the available route definitions. Specifies the pattern that can match a URL.
Rendering Renders the matched route branch. Supplies the element or nested route configuration for that route.
Example <Routes>...</Routes> <Route path="/about" element={...} />

13. Common Mistakes and Solutions

Problem Cause Solution
Route components do not work The route definitions are outside a router context. Wrap the application in BrowserRouter.
Incorrect component appears The path or element is configured incorrectly. Check the URL and route definitions.
Nested page is missing The parent layout does not include Outlet. Add Outlet where child content should render.
Navigation reloads the page Internal navigation uses a regular anchor element. Use React Router's Link for internal routes.
Unknown URL shows no custom message No fallback route has been defined. Add a route with path="*".
Refresh on a nested URL returns 404 The production server lacks SPA fallback configuration. Configure the server to serve the app entry HTML for client-side routes.

14. Best Practices

  • Keep route definitions organized and easy to maintain.
  • Use meaningful, consistent URL paths.
  • Use reusable layout components for shared page structures.
  • Use Outlet to render nested route content.
  • Use dynamic segments for values such as product IDs and user IDs.
  • Add a fallback route for unmatched URLs.
  • Use Link or NavLink for internal navigation.
  • Keep route components focused and reusable.
  • Test direct navigation, refresh behavior, and browser Back and Forward navigation.

15. Practical Project: Student Portal

Objective: Create a simple student portal with Home, Courses, Student Details, and a Not Found page.

Project Requirements

  1. Create a React project and install React Router.
  2. Wrap the application with BrowserRouter.
  3. Create Home and Courses components.
  4. Create a dynamic route for student details using /students/:studentId.
  5. Use Routes and Route to configure the URLs.
  6. Use Link to navigate between pages.
  7. Add a wildcard route for unknown URLs.
  8. Test all routes in the browser.

Example Route Configuration

import { Routes, Route } from "react-router";

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

function Courses() {
  return <h2>Available Courses</h2>;
}

function StudentDetails() {
  return <h2>Student Details</h2>;
}

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

function App() {
  return (
    <Routes>
      <Route path="/" element={<Home />} />
      <Route path="/courses" element={<Courses />} />
      <Route
        path="/students/:studentId"
        element={<StudentDetails />}
      />
      <Route path="*" element={<NotFound />} />
    </Routes>
  );
}

export default App;

16. Interview Questions and Answers

Q1. What is the purpose of Routes in React Router?

Answer: Routes selects and renders the route branch that best matches the current URL.

Q2. What does a Route component do?

Answer: A Route defines a URL pattern and the React element to render when the pattern matches.

Q3. Can we define multiple Route components?

Answer: Yes. Multiple Route components can be placed inside Routes to define different pages and URL patterns.

Q4. What is the purpose of the element prop?

Answer: The element prop specifies the React element that should render for a matching route.

Q5. What is a nested route?

Answer: A nested route is a child route defined inside a parent route. It can share the parent's layout and render through its Outlet.

Q6. What is a dynamic route?

Answer: A dynamic route contains a variable URL segment, such as /products/:productId, which can be read using useParams.

Q7. How do you handle an unknown URL?

Answer: Add a wildcard route using path="*" and render a custom Not Found component.

Q8. What is the difference between Link and Route?

Answer: Link allows users to navigate to a URL, while Route defines which element should render for a matching URL.

17. Learning Checklist

  • Understand the purpose of Routes and Route.
  • Understand the path and element props.
  • Configure multiple routes in one application.
  • Navigate between routes using Link.
  • Understand index routes and nested routes.
  • Use dynamic URL parameters.
  • Create a fallback 404 page.
  • Identify and fix common routing errors.

18. Conclusion

Routes and Route are the foundation of declarative routing in React Router. Routes selects the best matching route branch, while Route connects URL patterns to React elements. Together with BrowserRouter, Link, and Outlet, they help developers build structured, navigable React applications.

Learn more through JustAcademy React JS Training or Register for React JS Course Demo.

19. Official References

Previous Next
whatsapp