Nested router inside of Gatsby layout component

Viewed 1031

I'm wondering if it's possible to use nested routes inside of a Gatsby layout component? I know that the react reach router supports this, but I'm not quite sure how to get it working within Gatsby...

Currently I have a layout component that contains my site header and side navigation menu. Each page loads within the body of the layout correctly.

I'm trying to now create a tabbed interface within one of my MDX pages.

Is it possible to use a nested router, nested layout component, or any other mechanism to avoid reloading the whole body content (including the tabs) when changing pages?

I'm hoping that I can define sub-pages as MDX as well, and reference those as content to load for each of the tabs without reloading my main layout component, or current surrounding page content. Just curious if this is possible or if I should try to pursue a different approach.

Current layout hierarchy

<Root>
    /* AppLayout is static around ALL pages and contains header, navigation, and footer */
    <AppLayout>
        /* PageLayout is the wrapper around each MDX page content (which I want to contain the tabs) */
        <PageLayout>
            {MDX page content}
        </PageLayout>
    </AppLayout>
</Root>

Currently, <PageLayout> re-renders when I navigate to other pages (even when using <Link> component), <AppLayout> does not. This does make sense to me because each page is supposed to replace the content of <AppLayout>, but I'm curious if there is a way to either restructure this or use a different mechanism to achieve it.

I'm hoping to have <PageLayout> contain tabs within its content, but not have the rest of the content within that specific page re-render when switching tabs.

1 Answers

As far as I know, it should work no matter if you use Gatsby or a standalone reach-router implementation because Gatsby's routing extends from React reach-routing, adding some enhancements. According to their documentation:

The component is a wrapper around @reach/router’s Link component that adds useful enhancements specific to Gatsby. All props are passed through to @reach/router’s Link component.

Gatsby’s <Link> component enables linking to internal pages within a preloading, prefetching resources so that they are fetched by the time the user navigates with this component. We use an IntersectionObserver to fetch a low-priority request when the Link is in the viewport and then use an onMouseOver event to trigger a high-priority request when it is likely that a user will navigate to the requested resource

Related