React Router
What is the frontend router?
A path corresponds to a component. When we visit a path in the browser, the component corresponding to the path will be rendered on the page.
const routes = [
{
path: '/about',
component: About,
},
{
path: '/article',
component: Article,
},
];
React Router
react-router-dom
is a version of React Router tailored specifically for web applications. It provides DOM bindings for React Router, enabling efficient management of routes in a web environment. This package includes components and hooks that help in handling navigation and rendering components in web applications.
Components
- BrowserRouter: A
<Router>
that uses the HTML5 history API to keep your UI in sync with the URL. - HashRouter: A
<Router>
that uses the hash portion of the URL (i.e., window.location.hash) to keep your UI in sync. It's useful in scenarios where you do not have control over the server configuration. - Route: This component conditionally renders a part of your UI when the URL matches its path.
- Link: Renders a navigational link that allows for navigation to different routes defined in the application without a page reload.
- NavLink: Similar to
<Link>
, but it adds styling attributes to the rendered element when it matches the current URL.
Hooks
- useHistory: This hook gives access to the history instance used by React Router. Using
history
, you can navigate, go back, go forward, etc. In version 6 ofreact-router-dom
,useNavigate
replacesuseHistory
. - useLocation: Returns the location object representing the current URL. You can use this to read the current pathname, search, hash, etc.
- useParams: Returns an object of key/value pairs of URL parameters. Use it to access the parameters of the current route.
- useRouteMatch: Used to match the current URL similar to a
<Route>
. It's useful for building nested<Route>
components.
Version 6 Updates
In version 6 of react-router-dom
, there are significant changes and improvements:
- useNavigate: Replaces
useHistory
. It provides a function that lets you navigate programmatically. - Routes: Replaces
<Switch>
as the component that handles route matching and rendering. It renders the first matching route exclusively. - Element Prop: Instead of using
component
orrender
props for routing, version 6 useselement
prop to specify the component to render.
Example Usage
Here's a simple example of how to use react-router-dom
in a React application:
import React from 'react';
import ReactDOM from 'react-dom';
import { BrowserRouter, Routes, Route, Link } from 'react-router-dom';
function Home() {
return <h2>Home Page</h2>;
}
function About() {
return <h2>About Page</h2>;
}
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>
);
}
ReactDOM.render(<App />, document.getElementById('root'));
Basic Routing with React Router
Here's an example demonstrating basic routing setup using BrowserRouter
, Routes
, Route
, and Link
components, facilitating navigation between a Home page and an About page:
import React from 'react';
import ReactDOM from 'react-dom';
import { BrowserRouter, Routes, Route, Link } from 'react-router-dom';
function Home() {
return <h2>Home Page</h2>;
}
function About() {
return <h2>About Page</h2>;
}
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>
);
}
ReactDOM.render(<App />, document.getElementById('root'));
Parameter Passing in Route Navigation
1. Route Parameters
Route parameters allow dynamic path segments to be injected into your component based on the route.
Example:
<Route path='/user/:userId' element={<User />} />
Inside User
component:
const { userId } = useParams();
2. Query Parameters
Query parameters are used for optional data in the URL query string.
Example:
// Navigation: <Link to="/search?name=John">Search</Link>
const query = new URLSearchParams(useLocation().search);
const name = query.get('name');
3. State Parameters
Pass state to routes to send additional data.
Example:
// Navigation: <Link to={{ pathname: "/profile", state: { userId: 123 } }}>Profile</Link>
const location = useLocation();
const { userId } = location.state;
Nested Routes
React Router supports nested routes, which allow for more intricate application structures.
Example:
import {
BrowserRouter as Router,
Routes,
Route,
Outlet,
} from 'react-router-dom';
function App() {
return (
<Router>
<Routes>
<Route path='/' element={<Home />} />
<Route path='about' element={<About />}>
<Route path='team' element={<Team />} />
<Route path='company' element={<Company />} />
</Route>
</Routes>
</Router>
);
}
Handling 404 Pages
Setup a catch-all route to handle unmatched paths.
React Router v6 Example:
<Route path='*' element={<NotFoundPage />} />
Routing Strategies: History vs. Hash
- History Routing: Utilizes the HTML5 history API to manage the URL. Server-side support is required to handle deep linking.
- Hash Routing: Uses the URL hash. It's easier to manage on the server side but less elegant and potentially less SEO-friendly.
Routing Mode | URL Representation | Underlying Principle | Backend Support Required |
---|---|---|---|
history | /login | HTML5 history API | Yes |
hash | /#/login | URL hash | No |