How does React achieve nesting routes and dynamic route…
To achieve nested routing, you can use the React Router library. Here’s a simple example:
Firstly, install the React Router library.
npm install react-router-dom
Next, create a parent component with nested routes.
import React from 'react';
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
import Home from './Home';
import About from './About';
import Contact from './Contact';
import Products from './Products';
const App = () => {
return (
<Router>
<Switch>
<Route exact path="/" component={Home} />
<Route path="/about" component={About} />
<Route path="/contact" component={Contact} />
<Route path="/products" component={Products} />
</Switch>
</Router>
);
};
export default App;
In this example, we have defined four paths, each corresponding to a different component. Under the /products path, we can further define child routes.
Next, create a child component with dynamic routing.
import React from 'react';
import { Link, Route, Switch, useRouteMatch } from 'react-router-dom';
import ProductDetail from './ProductDetail';
import ProductList from './ProductList';
const Products = () => {
const { path, url } = useRouteMatch();
return (
<div>
<h2>Products</h2>
<ul>
<li>
<Link to={`${url}/product1`}>Product 1</Link>
</li>
<li>
<Link to={`${url}/product2`}>Product 2</Link>
</li>
</ul>
<Switch>
<Route exact path={path}>
<h3>Please select a product.</h3>
</Route>
<Route path={`${path}/:productId`} component={ProductDetail} />
</Switch>
</div>
);
};
export default Products;
In this example, we are using the useRouteMatch hook to access the parent component’s path and URL. When rendering the child components, we utilize dynamic routing parameters (:productId) to match different product details.
Finally, create a component for displaying product details.
import React from 'react';
import { useParams } from 'react-router-dom';
const ProductDetail = () => {
const { productId } = useParams();
return (
<div>
<h3>Product Detail - {productId}</h3>
{/* 显示产品详情 */}
</div>
);
};
export default ProductDetail;
This way, when you visit /products/product1, it will display Product Detail – product1.
With React Router’s route configuration and dynamic route parameters, we can achieve nested routes and dynamic routing.