Advanced Concepts

Nested Routes

Edit this page

Nested routes are a way to create a hierarchy of routes in your application. This is useful for creating a layout that is consistent across multiple pages, or for creating a relationship between pages that are related to each other.

In Solid Router, the following two route definitions have the same result:

<Route path="/users/:id" component={User} />
// is the same as
<Route path="/users">
<Route path="/:id" component={User} />
</Route>

The <User /> component will render when the URL is /users/:id in both cases. The difference is that in the first case, /users/:id is the only route, and in the second case, /users/ is also a route.

Leaf nodes, or innermost Route components, are the only ones that become their own route. If a parent Route component needs to be its own route, it must be specified separately:

// This won't work the way you'd expect
<Route path="/users" component={Users}>
<Route path="/:id" component={User} />
</Route>
// This works
<Route path="/users" component={Users} />
<Route path="/users/:id" component={User} />
// This also works
<Route path="/users">
<Route path="/" component={Users} />
<Route path="/:id" component={User} />
</Route>

Nesting through props.children

Nesting can be done through the use of props.children passed to the route component. This is useful for creating a layout that is consistent across multiple pages, or for creating a relationship between pages that are related to each other:

function PageWrapper(props) {
return (
<div>
<h1> We love our users! </h1>
{props.children}
<A href="/">Back Home</A>
</div>
);
}
<Route path="/users" component={PageWrapper}>
<Route path="/" component={Users} />
<Route path="/:id" component={User} />
</Route>;

While the routes are still configured the same, the route elements will appear inside the parent element where the props.children was declared.

Report an issue with this page