React Logoreact-router-dom

React Router DOM is a standard library for routing in React applications. It enables the creation of single-page applications (SPAs) where users can navigate between different views (components) without full page reloads. Instead of requesting a new HTML page from the server for each navigation, React Router DOM dynamically updates the URL and renders the appropriate UI component based on the current URL path.

Key features and components include:

1. BrowserRouter: The recommended router for web applications. It uses the HTML5 history API (pushState, replaceState, popState) to keep your UI in sync with the URL.
2. Routes: A component that acts as a container for individual `Route` components. It looks at all its children `Route`s and renders the first one whose path matches the current URL.
3. Route: This component defines a specific path and the element (component) to render when that path matches the current URL. It can also handle dynamic segments (e.g., `/users/:id`).
4. Link: Used to create navigatable links. It renders an `<a>` tag in the DOM but prevents the default browser behavior of full page reloads, instead using React Router DOM's internal routing mechanism.
5. NavLink: A special version of `Link` that automatically applies an `active` class (or a custom class/style) to the link when it matches the current URL, useful for highlighting the active navigation item.
6. useNavigate: A hook that provides a function to programmatically navigate to different routes.
7. useParams: A hook that allows access to dynamic parameters from the URL (e.g., `id` from `/users/:id`).
8. useLocation: A hook that returns the current location object, which contains information about the current URL (pathname, search query, hash, state).

React Router DOM is crucial for building user-friendly and performant SPAs by providing a declarative way to manage navigation and URL synchronization.

Example Code

import React from 'react';
import { BrowserRouter as Router, Routes, Route, Link, useParams, useNavigate } from 'react-router-dom';

// --- Component Definitions ---

const Home = () => (
  <div>
    <h2>Home Page</h2>
    <p>Welcome to the home page!</p>
  </div>
);

const About = () => (
  <div>
    <h2>About Page</h2>
    <p>Learn more about us here.</p>
  </div>
);

const Contact = () => {
  const navigate = useNavigate();

  const handleGoHome = () => {
    navigate('/'); // Programmatic navigation to the home page
  };

  return (
    <div>
      <h2>Contact Page</h2>
      <p>Feel free to reach out.</p>
      <button onClick={handleGoHome}>Go to Home</button>
    </div>
  );
};

const UserProfile = () => {
  const { id } = useParams(); // Get the dynamic 'id' parameter from the URL
  return (
    <div>
      <h2>User Profile</h2>
      <p>Viewing profile for user ID: {id}</p>
    </div>
  );
};

const NotFound = () => (
  <div>
    <h2>404 - Page Not Found</h2>
    <p>Sorry, the page you are looking for does not exist.</p>
  </div>
);

// --- Main App Component ---

function App() {
  return (
    <Router>
      <div>
        <nav>
          <ul>
            <li>
              <Link to="/">Home</Link>
            </li>
            <li>
              <Link to="/about">About</Link>
            </li>
            <li>
              <Link to="/contact">Contact</Link>
            </li>
            <li>
              <Link to="/user/123">User 123 Profile</Link>
            </li>
            <li>
              <Link to="/user/456">User 456 Profile</Link>
            </li>
            <li>
              <Link to="/non-existent-page">Broken Link</Link>
            </li>
          </ul>
        </nav>

        {/* A <Routes> looks through its children <Route>s and renders the first one that matches the current URL. */}
        <Routes>
          <Route path="/" element={<Home />} />
          <Route path="/about" element={<About />} />
          <Route path="/contact" element={<Contact />} />
          <Route path="/user/:id" element={<UserProfile />} /> {/* Dynamic route */}
          <Route path="*" element={<NotFound />} /> {/* Catch-all route for unmatched paths */}
        </Routes>
      </div>
    </Router>
  );
}

export default App;

// To run this example:
// 1. Create a new React app: `npx create-react-app my-router-app`
// 2. Navigate into the folder: `cd my-router-app`
// 3. Install react-router-dom: `npm install react-router-dom`
// 4. Replace the content of `src/App.js` with the code above.
// 5. Start the development server: `npm start`