Home  >  Article  >  Web Front-end  >  How do you structure nested routes in React Router v4 and v5?

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

DDD
DDDOriginal
2024-10-31 02:15:29389browse

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} />

Should be structured as follows:

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

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>

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!

Statement:
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