Building Single-Page Apps with React? Master Routing with React Router or React Router DOM

2024-07-27

  • Core Functionality: Provides the essential building blocks for implementing routing in React applications.
  • Components and Functions: Offers components like Route, Switch, Redirect, and functions like useHistory, useParams, and useLocation for defining routes, matching URLs to components, handling navigation, and accessing URL parameters.
  • Use Case: When you need fine-grained control over routing behavior or plan to use React Router in non-browser environments (like server-side rendering or React Native).
  • Browser-Specific Functionality: A sub-package of react-router that provides components and hooks specifically designed for web browser environments.
  • DOM-Aware Components: Includes components like <BrowserRouter>, <Link>, and <NavLink> that simplify routing setup and integrate seamlessly with the browser's DOM (Document Object Model), making navigation and URL updates more intuitive.
  • Convenience: Offers a more user-friendly experience for building web-based React applications with routing.
  • Use Case: The recommended choice for the vast majority of React web app development scenarios. It re-exports all of react-router's functionality, so you don't need to install both packages.

When to Use Which

In most cases, you'll want to use react-router-dom for your React web applications. It provides a streamlined approach to routing, including:

  • Easier navigation management with <Link> and <NavLink> components.
  • Automatic browser history management with <BrowserRouter>.
  • Access to URL parameters and other history-related information using hooks like useParams and useLocation.

Key Differences:

Featurereact-routerreact-router-dom
FunctionalityCore routing logicWeb browser-specific routing components and hooks
ComponentsRoute, Switch, Redirect, etc.<BrowserRouter>, <Link>, <NavLink>, etc.
EnvironmentCan be used in browser and non-browser environmentsPrimarily for web browsers
InstallationCan be installed directlyRecommended (installs react-router as a dependency)

In summary:

  • For most React web development, use react-router-dom. It provides a convenient and efficient way to handle routing in your application.
  • If you need more granular control or plan to use React Router in non-browser settings, consider using react-router directly.



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

function Home() {
  return (
    <div>
      <h2>Home</h2>
      <p>Welcome to the home page!</p>
      <Link to="/about">Go to About Page</Link>
    </div>
  );
}

function About() {
  return (
    <div>
      <h2>About</h2>
      <p>Learn more about us.</p>
      <Link to="/">Go to Home Page</Link>
    </div>
  );
}

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

export default App;

Explanation:

  • We import necessary components from react-router-dom.
  • Home and About components render content for their respective routes.
  • <BrowserRouter> wraps the entire application, providing the routing context.
  • <Routes> and nested <Route> components define the mapping between URLs and components to render.
  • <Link> components create clickable links that trigger navigation to other routes within the application.

Using <NavLink> for Styling:

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

// ... (component definitions)

function App() {
  return (
    <BrowserRouter>
      <nav>
        <NavLink to="/" activeClassName="active">
          Home
        </NavLink>
        <NavLink to="/about" activeClassName="active">
          About
        </NavLink>
      </nav>
      <Routes>
        <Route path="/" element={<Home />} />
        <Route path="/about" element={<About />} />
      </Routes>
    </BrowserRouter>
  );
}

export default App;
  • We replace <Link> with <NavLink> in the navigation bar.
  • We add the activeClassName prop to <NavLink> to apply a CSS class (e.g., "active") when the link's corresponding route is active, allowing for visual styling of active navigation elements.



While react-router-dom offers convenient components, you can achieve basic routing using hooks provided by react-router directly. This approach can be more lightweight but requires more manual setup:

import React from 'react';
import { useHistory } from 'react-router';

function Home() {
  const history = useHistory();

  const handleClickAbout = () => {
    history.push('/about');
  };

  return (
    <div>
      <h2>Home</h2>
      <p>Welcome to the home page!</p>
      <button onClick={handleClickAbout}>Go to About Page</button>
    </div>
  );
}

// ... (similar About component)

function App() {
  return (
    <div>
      <Home />
      {/* ... (other components) */}
    </div>
  );
}

export default App;
  • We import useHistory from react-router.
  • We use useHistory hook to access navigation methods like push for programmatic navigation.
  • This example demonstrates manual navigation rather than the declarative approach with <Link>.

Wouter (Minimalist Router)

Wouter is a lightweight alternative to react-router-dom that focuses on simplicity and basic routing functionalities:

import React from 'react';
import { useRouter } from 'wouter';

function Home() {
  const [location, navigate] = useRouter();

  const handleClickAbout = () => {
    navigate('/about');
  };

  return (
    <div>
      <h2>Home</h2>
      <p>Welcome to the home page!</p>
      <button onClick={handleClickAbout}>Go to About Page</button>
      <p>Current location: {location.pathname}</p>
    </div>
  );
}

// ... (similar About component)

function App() {
  return (
    <div>
      <Home />
      {/* ... (other components) */}
    </div>
  );
}

export default App;
  • We import useRouter from wouter.
  • useRouter provides an array with location (current path) and navigate (navigation function) for programmatic navigation.
  • This example is similar to using hooks from react-router directly, but with some syntax differences.

Choosing an Alternate Method:

  • If you prefer a lightweight approach with less overhead, Wouter could be a good option.
  • If you need more advanced features beyond basic routing or are already using react-router for non-browser environments, using hooks with react-router directly might be more suitable.

reactjs react-router



Understanding React JSX: Selecting "selected" on a Selected <select> Option

Understanding the <select> Element:The <select> element in HTML represents a dropdown list.It contains one or more <option> elements...


Understanding Virtual DOM: The Secret Behind React's Performance

Imagine the Virtual DOM (VDOM) as a lightweight, in-memory copy of your React application's actual DOM (Document Object Model). It's a tree-like structure that mirrors the elements on your web page...


Keeping Your React Components Clean: Conditional Rendering and DRY Principles

ReactJS provides several ways to conditionally render elements based on certain conditions. Here are the common approaches:...


Understanding Parent-Child Communication in React: The Power of Props

Here's a breakdown of the process:Parent Component:Define the data you want to pass as props within the parent component...


React: Why You Can't Use 'for' Attribute Directly on Label Elements

In JavaScript, for is a reserved keyword used for loop constructs.When you directly use for as an attribute in JSX (React's syntax for creating HTML-like elements), it conflicts with this keyword's meaning...



reactjs react router

Beyond window.resize: Effective Methods for Responsive Layouts in React

When a user resizes the browser window, you want your React application to adapt its layout and elements accordingly. This ensures a visually appealing and functional experience across different screen sizes


Accessing Custom Attributes from Event Handlers in React

React allows you to define custom attributes on HTML elements using the data-* prefix. These attributes are not part of the standard HTML specification and are used to store application-specific data


Unveiling the Secrets of React's Performance: How Virtual DOM Beats Dirty Checking

Directly updating the DOM (Document Object Model) in JavaScript can be slow. The DOM represents the structure of your web page


Communicating Between React Components: Essential Techniques

React applications are built from independent, reusable components. To create a cohesive user experience, these components often need to exchange data or trigger actions in each other


Unlocking Dynamic Content in React: Including Props Within JSX Quotes

In React, components can receive data from parent components through properties called props.These props allow you to customize the behavior and appearance of child components