5

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!

ETNs
  • 103
  • 1
  • 8

2 Answers2

7

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>
Ramakay
  • 2,919
  • 1
  • 5
  • 21
0

Update for NextJS 13 and above

NextJS team shipped a new type of router called App Router in version 13.

It's built on React server components and supports shared layout, nested routing and has lots of other super-useful features !

Check it out : https://nextjs.org/docs/app/building-your-application/routing#the-app-router

ETNs
  • 103
  • 1
  • 8