Home > Article > Web Front-end > Senior level: Routing with React Router
As a senior-level developer, it's crucial to have a comprehensive understanding of routing in React applications. React Router provides a robust solution for managing navigation and rendering of components based on URL paths. This guide covers the setup of React Router, essential components, and advanced techniques such as nested routes, dynamic routing, route parameters, and route guards.
React Router is a powerful library for handling client-side routing in React applications. It allows for dynamic routing, nested routes, and conditional rendering based on the URL path.
First, install React Router using npm or yarn:
npm install react-router-dom
or
yarn add react-router-dom
React Router provides several components to define routes and handle navigation.
The Route component is used to define a path and associate it with a component.
Example:
import React from 'react'; import { BrowserRouter as Router, Route } from 'react-router-dom'; import Home from './Home'; import About from './About'; const App = () => { return ( <Router> <Route path="/" exact component={Home} /> <Route path="/about" component={About} /> </Router> ); }; export default App;
The Switch component ensures that only one route is rendered at a time, matching the first route that fits.
Example:
import React from 'react'; import { BrowserRouter as Router, Route, Switch } from 'react-router-dom'; import Home from './Home'; import About from './About'; import NotFound from './NotFound'; const App = () => { return ( <Router> <Switch> <Route path="/" exact component={Home} /> <Route path="/about" component={About} /> <Route component={NotFound} /> </Switch> </Router> ); }; export default App;
The Link component creates navigational links, preventing full page reloads and preserving the single-page application experience.
Example:
import React from 'react'; import { BrowserRouter as Router, Route, Link } from 'react-router-dom'; import Home from './Home'; import About from './About'; const App = () => { return ( <Router> <nav> <Link to="/">Home</Link> <Link to="/about">About</Link> </nav> <Route path="/" exact component={Home} /> <Route path="/about" component={About} /> </Router> ); }; export default App;
The NavLink component is similar to Link but allows for styling based on the active route.
Example:
import React from 'react'; import { BrowserRouter as Router, Route, NavLink } from 'react-router-dom'; import Home from './Home'; import About from './About'; const App = () => { return ( <Router> <nav> <NavLink exact to="/" activeClassName="active"> Home </NavLink> <NavLink to="/about" activeClassName="active"> About </NavLink> </nav> <Route path="/" exact component={Home} /> <Route path="/about" component={About} /> </Router> ); }; export default App;
Nested routes allow you to create routes within other routes, which is useful for complex layouts with sub-navigation.
Example:
import React from 'react'; import { BrowserRouter as Router, Route, Switch, Link, useRouteMatch } from 'react-router-dom'; const Topic = ({ match }) => <h3>Requested Topic ID: {match.params.topicId}</h3>; const Topics = () => { let { path, url } = useRouteMatch(); return ( <div> <h2>Topics</h2> <ul> <li> <Link to={`${url}/components`}>Components</Link> </li> <li> <Link to={`${url}/props-v-state`}>Props v. State</Link> </li> </ul> <Switch> <Route exact path={path}> <h3>Please select a topic.</h3> </Route> <Route path={`${path}/:topicId`} component={Topic} /> </Switch> </div> ); }; const App = () => ( <Router> <div> <ul> <li> <Link to="/">Home</Link> </li> <li> <Link to="/topics">Topics</Link> </li> </ul> <Switch> <Route exact path="/"> <h2>Home</h2> </Route> <Route path="/topics" component={Topics} /> </Switch> </div> </Router> ); export default App;
Dynamic routing allows creating routes based on dynamic parameters, useful for user profiles or product details.
Example:
import React from 'react'; import { BrowserRouter as Router, Route, Switch, Link } from 'react-router-dom'; const User = ({ match }) => <h3>User ID: {match.params.userId}</h3>; const App = () => ( <Router> <div> <ul> <li> <Link to="/user/1">User 1</Link> </li> <li> <Link to="/user/2">User 2</Link> </li> </ul> <Switch> <Route path="/user/:userId" component={User} /> </Switch> </div> </Router> ); export default App;
Route parameters allow capturing values from the URL to be used in components.
Example:
import React from 'react'; import { BrowserRouter as Router, Route, Switch, Link } from 'react-router-dom'; const Product = ({ match }) => <h3>Product ID: {match.params.productId}</h3>; const App = () => ( <Router> <div> <ul> <li> <Link to="/product/101">Product 101</Link> </li> <li> <Link to="/product/202">Product 202</Link> </li> </ul> <Switch> <Route path="/product/:productId" component={Product} /> </Switch> </div> </Router> ); export default App;
Route guards restrict access to certain routes based on conditions such as user authentication.
Example:
import React from 'react'; import { BrowserRouter as Router, Route, Redirect } from 'react-router-dom'; const isAuthenticated = false; const PrivateRoute = ({ component: Component, ...rest }) => ( <Route {...rest} render={(props) => isAuthenticated ? <Component {...props} /> : <Redirect to="/login" /> } /> ); const Dashboard = () => <h3>Dashboard</h3>; const Login = () => <h3>Login</h3>; const App = () => ( <Router> <div> <PrivateRoute path="/dashboard" component={Dashboard} /> <Route path="/login" component={Login} /> </div> </Router> ); export default App;
Redirects can navigate users to different routes programmatically.
Example:
import React from 'react'; import { BrowserRouter as Router, Route, Redirect, Switch } from 'react-router-dom'; const OldPage = () => <h3>Old Page (will redirect)</h3>; const NewPage = () => <h3>New Page</h3>; const App = () => ( <Router> <Switch> <Route path="/old-page"> <Redirect to="/new-page" /> </Route> <Route path="/new-page" component={NewPage} /> </Switch> </Router> ); export default App;
In this example, visiting /old-page automatically redirects the user to /new-page.
Mastering routing with React Router is essential for building sophisticated and user-friendly React applications. Understanding how to set up routes, use core components, and implement advanced techniques such as nested routes, dynamic routing, route parameters, and route guards will enable you to create robust navigation systems. As a senior developer, these skills will help you design and implement scalable routing architectures in your React projects, ensuring a seamless user experience and maintainable codebase.
The above is the detailed content of Senior level: Routing with React Router. For more information, please follow other related articles on the PHP Chinese website!