Search code examples
reactjsroutesreact-routerreach-router

How do I use different layouts in Reach Router?


I have an app where I have N different layouts (eg. BeforeLogin, MainLayout, SomeElseLayout, etc.).

Each layout is an HTML-markup component that should wrap a page-component, like Settings, Profile, etc.

I need to be able to assign a specific layout to each of my routes (or a groups of routes).

For instance, I want URLs

/register
/info/*
/about

... to use BeforeLogin layout component (to be children of), and

/dashboard
/profile/*
/settings/*

...to use MainLayout.

Also, some URLs, like / might use one layout before user logs-in in and another after. But that, I presume, will be possible to achieve with conditional rendering once the main question is answered.

So the question is - How do I do that?

(besides, of course, rendering the layout within each page-component explicitly, I would prefer my components to be layout-agnostic)

Thanks!

P.S. For those who missed, the question is about Reach router, not React Router.


Solution

  • You could easily create multiple HOC where each would represent one of your layout components. Then you'd just wrap component you want with desired layout:

    const withMainLayout = (Component) => (props) => {
        return (
            <MainLayout>
                <Component {...props} />
            </MainLayout>
        )
    }
    

    And then you would use it like

    const LayoutDashboard = withMainLayout(DashboardComponent);
    

    This way you can create X layout and corresponding HOC's and then just wrap desired components.