Home > Article > Web Front-end > How to Implement Nested Routing in React Router v4/v5?
React Router provides a powerful mechanism for creating nested routes within your React applications. This allows you to modularize your routes and create complex navigation structures.
To create nested routes in React Router v4, you would define a parent route and specify child routes within it. For example, to separate your app into frontend and admin sections:
<code class="jsx"><Match pattern="/" component={Frontpage}> <Match pattern="/home" component={HomePage} /> <Match pattern="/about" component={AboutPage} /> </Match> <Match pattern="/admin" component={Backend}> <Match pattern="/home" component={Dashboard} /> <Match pattern="/users" component={UserPage} /> </Match> <Miss component={NotFoundPage} /></code>
However, it's important to note that in React Router v4, routes are not nested within other routes. Instead, child routes are placed inside a parent component. Thus, the above code would be converted to:
<code class="jsx"><Route path="/" component={Frontpage} /></code>
With this parent component:
<code class="jsx">const Frontpage = ({ match }) => ( <div> <h2>Frontend</h2> <Link to={`${match.url}/home`}>Home</Link> <Link to={`${match.url}/about`}>About</Link> <Route path={`${match.path}/home`} component={HomePage} /> <Route path={`${match.path}/about`} component={AboutPage} /> </div> );</code>
Similarly, for the admin section:
<code class="jsx"><Route path="/admin" component={Backend} /></code>
With this parent component:
<code class="jsx">const Backend = ({ match }) => ( <div> <h2>Admin</h2> <Link to={`${match.url}/home`}>Dashboard</Link> <Link to={`${match.url}/users`}>Users</Link> <Route path={`${match.path}/home`} component={Dashboard} /> <Route path={`${match.path}/users`} component={UserPage} /> </div> );</code>
This approach allows you to create modular and reusable components that encapsulate both route definitions and UI rendering for different sections of your application.
The above is the detailed content of How to Implement Nested Routing in React Router v4/v5?. For more information, please follow other related articles on the PHP Chinese website!