Home > Web Front-end > JS Tutorial > body text

How do you structure nested routes in React Router v4 and v5?

DDD
Release: 2024-10-31 02:15:29
Original
388 people have browsed it

How do you structure nested routes in React Router v4 and v5?

Nested Routes in React Router

In React Router versions 4 and 5, nesting routes involves a slightly different approach. Instead of nesting components, you place them within another .

For example, the following nested route configuration:

<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} />
Copy after login

Should be structured as follows:

<Route path="/" component={Frontpage} />
<Route path="/admin" component={Backend} />
Copy after login

Within these components, you can define the child routes as subcomponents of the parent component, as demonstrated in this example:

<code class="javascript">const Frontpage = ({ match }) => (
  <div>
    {/* Child routes for the frontend */}
    <Link to={`${match.url}/home`}></Link>
    <Link to={`${match.url}/about`}></Link>
    <Route path={`${match.path}/home`} component={HomePage} />
    <Route path={`${match.path}/about`} component={AboutPage} />
  </div>
);

const Backend = ({ match }) => (
  <div>
    {/* Child routes for the admin area */}
    <Link to={`${match.url}/home`}></Link>
    <Link to={`${match.url}/users`}></Link>
    <Route path={`${match.path}/home`} component={Dashboard} />
    <Route path={`${match.path}/users`} component={UserPage} />
  </div>
);</code>
Copy after login

This revised structure ensures that /home within the frontend component is accessible at /, while /admin/home within the backend component is accessible at /admin/home.

The above is the detailed content of How do you structure nested routes in React Router v4 and v5?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!