React Router DOM

React Router DOM

React Router DOM is a widely used library for handling routing in React applications, particularly those designed for web browsers. It provides a set of components and hooks that enable declarative navigation and URL management within single-page applications (SPAs).

Key features and functionalities of React Router DOM:

Installation:

To use React Router DOM in a React project, it needs to be installed as a dependency:


Code

npm install react-router-dom
Basic Usage Example:
Code

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

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

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

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

export default App;

Note on React Router v7:

With React Router v7, the react-router-dom package primarily re-exports the contents of react-router. While react-router-dom can still be used for compatibility with older projects or during upgrades, new projects are encouraged to use react-router directly for web applications, as the browser-specific functionalities are now integrated within the core react-router package

 


react-router-dom enables declarative, component-based routing in React web apps, allowing single-page applications (SPAs) to navigate between different views/components without full page reloads, managing browser history, supporting dynamic URLs (with parameters), creating nested routes for complex layouts, handling authentication (route guards), and providing tools for bookmarkable links and programmatic navigation via hooks like useNavigate (formerly useHistory) and useLocation, all through DOM-aware components like <BrowserRouter>, <Link>, and <Route>. 


This video provides a complete tutorial on the basics of React Router:

Core Uses & Features

You can watch this video to see how to perform simple navigation between pages in React:

Key Components & Hooks (v6+)


When to Use It

This video provides a complete tutorial on the basics of React Router:
GreatStack
YouTube • 9 Oct 2024

 

 

 

import { RouterProvider } from "react-router-dom"


The import { RouterProvider } from "react-router-dom"; statement is used in React applications to import the RouterProvider component from the react-router-dom library.

Functionality of RouterProvider:

  • Provides the Router Context: The RouterProvider component is a core part of React Router v6. It acts as a wrapper for your entire application or the section of your application where routing is managed. It provides the router context to all nested components, allowing them to access routing functionalities like navigation, route matching, and data loading (with v6.4+ data APIs).

  • Receives a Router Object: It takes a router prop, which is an object created using one of React Router's router creation functions, such as createBrowserRouter or createHashRouter. This router object contains the definition of your application's routes.

  • Enables Data APIs: When used with createBrowserRouter, RouterProvider enables the use of React Router's data APIs (loaders, actions, fetchers) for efficient data management within your routes.

  • Centralized Route Management: By wrapping your application with RouterProvider, you centralize the management of your application's routing logic, making it easier to define, organize, and maintain your routes.

Example Usage: 
Code

import React from "react";
import ReactDOM from "react-dom/client";
import { createBrowserRouter, RouterProvider } from "react-router-dom";
import App from "./App";
import About from "./About";
import Contact from "./Contact";

const router = createBrowserRouter([
  {
    path: "/",
    element: <App />,
  },
  {
    path: "/about",
    element: <About />,
  },
  {
    path: "/contact",
    element: <Contact />,
  },
]);

ReactDOM.createRoot(document.getElementById("root")).render(
  <React.StrictMode>
    <RouterProvider router={router} />
  </React.StrictMode>
);

import {createBrowserRouter, Navigate} from "react-router-dom";

This JavaScript line imports createBrowserRouter for setting up application-wide routing and Navigate for programmatic redirection within React Router (v6+), allowing you to define routes and easily redirect users based on conditions or actions in your web application. It's used to configure your app's navigation structure and conditionally send users to different pages or paths. 


createBrowserRouter: Setting Up Routes

Navigate: Programmatic Redirection


javascript
import { Navigate } from 'react-router-dom';

function ProtectedRoute({ children }) {
  const isAuthenticated = checkAuthStatus(); // Your auth logic
  if (!isAuthenticated) {
    return <Navigate to="/login" replace />; // Redirect if not logged in
  }
  return children;
}

// In your router:
{ path: '/dashboard', element: <ProtectedRoute><Dashboard /></ProtectedRoute> }

navigate in react router dom

React Router DOM provides two primary mechanisms for programmatic navigation: the useNavigate hook and the Navigate component.
1. useNavigate Hook:
The useNavigate hook is used within functional components to obtain a navigate function, which can then be called to programmatically change the route. This is ideal for navigation triggered by events like button clicks, form submissions, or other interactive user actions.
Code

import { useNavigate } from 'react-router-dom';

function MyComponent() {
  const navigate = useNavigate();

  const handleClick = () => {
    navigate('/dashboard'); // Navigates to the /dashboard path
  };

  const handleLoginSuccess = () => {
    navigate('/home', { replace: true }); // Navigates to /home and replaces the current history entry
  };

  const goBack = () => {
    navigate(-1); // Navigates back one step in browser history
  };

  return (
    <button onClick={handleClick}>Go to Dashboard</button>
  );
}
2. Navigate Component:
The Navigate component is used for declarative navigation, typically for redirects based on certain conditions during the render process. It automatically navigates the user when rendered.
Code

import { Navigate } from 'react-router-dom';

function ProtectedRoute({ isAuthenticated }) {
  if (!isAuthenticated) {
    return <Navigate to="/login" replace />; // Redirects to /login if not authenticated
  }
  return <div>Protected content</div>;
}
Key Differences: 
useNavigate (Imperative): Used for navigation triggered by events or logic within a function.
Navigate (Declarative): Used for conditional or automatic navigation during the rendering of a component.

import { useOutletContext } from "react-router-dom";

import { useOutletContext } from "react-router-dom";

imports a React Router hook that lets child route components access data (like state or functions) passed down from a parent route using the <Outlet context={...} /> prop, avoiding prop drilling and simplifying data sharing in nested routes. This hook provides a convenient way to share dynamic data between parent layouts and their nested content, making it ideal for managing user info, theme settings, or data fetching states across different views. 



How it works

  1. Parent Route (e.g., DashboardLayout.js): Renders the <Outlet> component and passes data to its context prop.

    import { Outlet } from 'react-router-dom';
    function DashboardLayout() {
      const [user, setUser] = React.useState({ name: 'Alice' });
      return (
        <div>
          <h1>Dashboard</h1>
          {/* Pass data (or state/setters) through context */}
          <Outlet context={{ user, setUser }} />
        </div>
      );
    }
    
  2. Child Route (e.g., Profile.js): Uses useOutletContext() to get the passed data.

import { useOutletContext } from 'react-router-dom';
function Profile() {
  // Destructure data from the context
  const { user, setUser } = useOutletContext();
  return (
    <div>
      <p>Welcome, {user.name}</p>
      <button onClick={() => setUser({ name: 'Bob' })}>Change User</button>
    </div>
  );
}

 


Key benefits