React Router DOM
- React Router DOM
- import { RouterProvider } from "react-router-dom"
- import {createBrowserRouter, Navigate} from "react-router-dom";
- navigate in react router dom
- import { useOutletContext } from "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:
- Declarative Routing: It allows defining routes as components, making the routing logic intuitive and integrated with the React component tree.
-
Browser-Specific Components: It includes components like <BrowserRouter>, <Link>, and <NavLink> that specifically interact with the browser's history API and render standard HTML elements for navigation.
-
Dynamic Routing: Enables the creation of routes with dynamic parameters, allowing for flexible URL structures and data fetching based on the route.
-
Nested Routes: Supports the creation of hierarchical routes, where parent routes can render child routes, facilitating complex application layouts.
-
Programmatic Navigation: Provides hooks like useNavigate for imperative navigation, allowing redirection or programmatically changing routes based on user actions or application logic.
-
Route Guards and Authentication: Can be used to implement route protection, ensuring users are authenticated or authorized before accessing certain parts of the application.
Installation:
To use React Router DOM in a React project, it needs to be installed as a dependency:
npm install react-router-dom
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>.
- Client-Side Routing: Maps URLs to specific components, rendering them without server requests, perfect for SPAs.
- No Page Reloads: Smooth transitions between "pages" using JavaScript, enhancing user experience.
- URL Management: Creates clean, bookmarkable URLs and uses the browser's history stack.
- Declarative Routing: Defines routes using components like
<BrowserRouter>,<Routes>, and<Route>. - Dynamic Routes: Handles URLs with parameters (e.g.,
/users/:id) to show dynamic content. - Nested Routes: Organizes complex UIs by rendering child routes within parent routes.
- Programmatic Navigation: Navigate programmatically with useNavigate (or
useHistory) or declaratively with<Navigate>. - Data Loading: Modern versions (v7+) allow data fetching directly in route definitions (loaders/actions).
<BrowserRouter>: The main router that uses the HTML5 History API.<Routes>/<Route>: Renders components for matching paths.<Link>/<NavLink>: Renders<a>tags for navigation without page reloads.useNavigate: Hook for imperative navigation.useParams: Hook to access dynamic URL parameters.useLocation: Hook to get current location data.Outlet: Renders nested child routes.
- Web Applications: Use
react-router-domfor any React app running in a web browser. - Complex Layouts: Ideal for apps with dashboards, multi-step forms, or admin panels.
- Single-Page Apps (SPAs): Essential for building SPAs that feel like traditional multi-page sites.
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.
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
-
Purpose: Creates a history object for typical browser navigation (using the History API) and enables powerful data APIs (loaders, actions).
-
Usage: You pass an array of route objects (defining paths and elements to render) to it, then wrap your app with <RouterProvider router={router}>. .
javascript
import { createBrowserRouter, RouterProvider } from 'react-router-dom'; import { HomePage } from './pages/HomePage'; import { AboutPage } from './pages/AboutPage'; const router = createBrowserRouter([ { path: '/', element: <HomePage /> }, { path: '/about', element: <AboutPage /> }, ]); function App() { return <RouterProvider router={router} />; }
-
Purpose: A component that renders a <100ms 301 redirect when mounted, useful for authenticated routes or after form submissions.
-
Usage: Place it inside a component to redirect to a specific to path; use replace to avoid adding to history (e.g., for auth).
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
useNavigate hook and the Navigate component. 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>
);
}
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>;
}
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.
- Parent Route (e.g.,
DashboardLayout.js): Renders the<Outlet>component and passes data to itscontextprop.
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> ); } - Child Route (e.g.,
Profile.js): UsesuseOutletContext()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>
);
}
- Avoids Prop Drilling: Data is accessible to any nested component without passing it through every intermediate component.
- Centralized Data: Parent routes manage state or data needed by multiple children.
- TypeScript Friendly: Can be easily typed for better development experience