Building Single-Page Apps with React? Master Routing with React Router or React Router DOM
- Core Functionality: Provides the essential building blocks for implementing routing in React applications.
- Components and Functions: Offers components like
Route
,Switch
,Redirect
, and functions likeuseHistory
,useParams
, anduseLocation
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
anduseLocation
.
Key Differences:
Feature | react-router | react-router-dom |
---|---|---|
Functionality | Core routing logic | Web browser-specific routing components and hooks |
Components | Route , Switch , Redirect , etc. | <BrowserRouter> , <Link> , <NavLink> , etc. |
Environment | Can be used in browser and non-browser environments | Primarily for web browsers |
Installation | Can be installed directly | Recommended (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
andAbout
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
fromreact-router
. - We use
useHistory
hook to access navigation methods likepush
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
fromwouter
. useRouter
provides an array withlocation
(current path) andnavigate
(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 withreact-router
directly might be more suitable.
reactjs react-router