Search code examples
layoutnext.jsnext-router

How to apply a layout to all routes in a /pages' subfolder?


I created some routes in the /pages (next.js) folder and a subfolder /account. I want to apply a layout to all pages located in /account subfolder.

How can I do that easily without applying the layout to every single page in /account ?

Example

I want to apply a layout to profile.js and settings.js.

components/
pages/
 - home.js
 - account/
    - profile.js
    - settings.js
...

Any suggestion regarding the architecture will be appreciated!


Solution

  • You might need to create a custom app and load the layout based on the route - use below as an approach.

    i.e

    // pages/_app.js
    import Layout from '../components/layout'
    import AccountLayout from '../components/Accountlayout'
    
    export default function MyApp({ Component, pageProps, router }) {
    
        if (router.pathname.startsWith('/account/')) {
    
            return (
                <AccountLayout>
                    <Component {...pageProps} />
                </AccountLayout>
            )
    
        }
        return (
            <Layout>
              <Component {...pageProps} />
            </Layout>
        )
    }
    
    

    Optimizations possible...

    In the above code, you can use header footer as common between account and onn-account layouts, say an GlobalLayout - eventually it would become something like

    <GlobalLayout>
    <Layout> OR <AccountLayout>
    <Component {...pageProps} />
    </Layout> or </AccountLayout>
    </GlobalLayout>