Nested Routes
Sometimes, a nested useRoutes
call is useful. If a component rendered under useRoutes
makes another call of useRoutes
, routes rendered by the secondary call are automatically treated as children of the parent route. Child route builders should be hidden inside a component so that the child routes are only accessible during the component is rendered.
This is an example of a tab UI like this page. Notably, the PageWithTab
has no knowledge of what current location is. It only defines a Search route with the tab
search key.
Rocon implicitly combines this information with a parent route to generate a URL like /tutorial/nested?tab=tab2
.
const PageWithTab: React.FC = () => {
const tabRoute = useMemo(() => {
return Rocon.Search("tab", { optional: true }).action(({ tab }) => (
<Tabs tab={tab} tabRoute={tabRoute.route} />
));
}, []);
return useRoutes(tabRoute);
};
const Tabs: React.FC<{
tab: string | undefined;
tabRoute: ReactRouteRecord<{ tab: string | undefined }>;
}> = ({ tab = "tab1", tabRoute }) => {
return (
<div>
<nav>
<Link route={tabRoute} match={{ tab: "tab1" }}>Go to Tab1</Link>
<Link route={tabRoute} match={{ tab: "tab2" }}>Go to Tab2</Link>
<Link route={tabRoute} match={{ tab: "tab3" }}>Go to Tab3</Link>
</nav>
<p>Welcome to {tab}</p>
</div>
);
};
One thing to note is that, as an obvious conclusion of tabRoute
being enclosed in the PageWithTab
, there is no means to directly link to Tab 2 or Tab 3 from outside. If you need to do so, the tabRoute
route builder must be moved out of this component and attached to the parent route. Nested useRoutes
is useful if you really want to hide the sub-routes from its parent.