React Router

React Router is a powerful library for managing navigation and routing in React applications. It enables you to create single-page applications (SPAs) with dynamic navigation, allowing users to switch between views without reloading the page.

Syntax and Structure for Routes in React

Step 1: Install React Router

Open your terminal in the project directory and run the following command:

</>
Copy
npm install react-router-dom

If you are using Yarn, run:

</>
Copy
yarn add react-router-dom

Import Required Components

</>
Copy
import { BrowserRouter as Router, Routes, Route } from 'react-router-dom';
  • Router: The main wrapper that provides routing capabilities. Monitors the browser’s URL and synchronizes it with the displayed components.
  • Routes: A container for all Route components. Evaluates all the defined <Route> paths and determines which component to render based on the current URL.
  • Route: Defines the mapping between a specific URL path and a React component. When the URL matches the path value, the component specified in element is rendered.

Basic Route Structure

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


1. Example: Basic Routing

In this example, we demonstrate basic routing using React Router. We define three routes that render different components when navigating to specific URLs.

App.js

</>
Copy
import React from 'react';
    import { BrowserRouter as Router, Routes, Route, Link } from 'react-router-dom';

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

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

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

function App() {
  return (
    <Router>
      <nav>
        <Link to="/">Home</Link> | <Link to="/about">About</Link> | <Link to="/contact">Contact</Link>
      </nav>
      <Routes>
        <Route path="/" element=<Home /> />
        <Route path="/about" element=<About /> />
        <Route path="/contact" element=<Contact /> />
      </Routes>
    </Router>
  );
}

export default App;

Explanation:

  • BrowserRouter: Wraps the application to enable routing functionality.
  • Link: Provides navigation links without refreshing the page.
  • Routes and Route: Define the mapping between paths and components.
  • This setup allows seamless navigation between different views.

Output:


2. Nested Routes

Nested routes in React Router allow you to define a hierarchy of routes. They are particularly useful when building applications with nested UI components, such as dashboards with subsections or categories with subcategories.

Example

This example demonstrates nested routes, which allow you to create routes within routes. Here, we are creating hierarchical navigation structures.

App.js

</>
Copy
import React from 'react';
import { BrowserRouter as Router, Routes, Route, Link } from 'react-router-dom';

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

function Profile() {
  return <h2>User Profile</h2>;
}

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

function User() {
  return (
    <div>
      <h2>User Page</h2>
      <nav>
        <Link to="profile">Profile</Link> | <Link to="settings">Settings</Link>
      </nav>
      <Routes>
        <Route path="profile" element=<Profile /> />
        <Route path="settings" element=<Settings /> />
      </Routes>
    </div>
  );
}

function App() {
  return (
    <Router>
      <nav>
        <Link to="/dashboard">Dashboard</Link> | <Link to="/user">User</Link>
      </nav>
      <Routes>
        <Route path="/dashboard" element=<Dashboard /> />
        <Route path="/user/*" element=<User /> />
      </Routes>
    </Router>
  );
}

export default App;

Explanation:

  • Route path="/user/*": Specifies a parent route with nested child routes.
  • Nested Routes: Define routes relative to the parent path.
  • This approach creates a hierarchical navigation structure within the application.

Output:


3. Redirecting

Redirecting is useful when you want to navigate users to a different route programmatically.

Example

This example shows how to redirect users from one route to another.

App.js

</>
Copy
import React from 'react';
import { BrowserRouter as Router, Routes, Route, Navigate } from 'react-router-dom';

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

function OldPage() {
  return <Navigate to="/" replace />;
}

function App() {
  return (
    <Router>
      <Routes>
        <Route path="/" element=<Home /> />
        <Route path="/old" element=<OldPage /> />
      </Routes>
    </Router>
  );
}

export default App;

Explanation:

  • Navigate: Redirects the user to the specified path.
  • replace: Ensures that the redirected route replaces the current route in the history stack.
  • This approach is useful for deprecated URLs or automatic navigation.

Output:


4. Using URL Parameters

URL parameters in React Router allow you to create dynamic routes that include variable segments. This is particularly useful when rendering details for items such as products, users, or posts based on an identifier in the URL.

Example

This example demonstrates how to handle dynamic paths with URL parameters.

App.js

</>
Copy
import React from 'react';
import { BrowserRouter as Router, Routes, Route, useParams } from 'react-router-dom';

function Product() {
  const { id } = useParams();
  return <h2>Product ID: {id}</h2>;
}

function App() {
  return (
    <Router>
      <Routes>
        <Route path="/product/:id" element=<Product /> />
      </Routes>
    </Router>
  );
}

export default App;

Explanation:

  • useParams: Retrieves the dynamic parameter value from the URL.
  • :id: Specifies a dynamic segment in the route path.
  • This approach is useful for pages that display details based on identifiers.

Output:


Conclusion

React Router provides powerful tools to build dynamic, user-friendly navigation for your React applications. By understanding how to use basic routing, nested routes, redirection, and URL parameters, you can create seamless and responsive single-page applications. Practice these examples to master routing in React.