Home > OS >  Nextjs pages in folder share container
Nextjs pages in folder share container

Time:10-04

Is there any way to make all the pages in a folder share a container in NextJS?

I imagine it'd look something like this:

// pages/folder/index.js
export default function Container({ children }) {
    return <Container>{children}</Container>
}

// pages/folder/child.js
export default function Child() {
    return <Child />
}

CodePudding user response:

I believe what you're looking for is Layouts.

// components/layout.js

import Navbar from './navbar'
import Footer from './footer'

export default function Layout({ children }) {
  return (
    <>
      <Navbar />
      <main>{children}</main>
      <Footer />
    </>
  )
}

Single Shared Layout with Custom App

// pages/_app.js

import Layout from '../components/layout'

export default function MyApp({ Component, pageProps }) {
  return (
    <Layout>
      <Component {...pageProps} />
    </Layout>
  )
}

Per-Page Layouts

// pages/index.js

import Layout from '../components/layout'
import NestedLayout from '../components/nested-layout'

export default function Page() {
  return (
    /** Your content */
  )
}

Page.getLayout = function getLayout(page) {
  return (
    <Layout>
      <NestedLayout>{page}</NestedLayout>
    </Layout>
  )
}
// pages/_app.js

export default function MyApp({ Component, pageProps }) {
  // Use the layout defined at the page level, if available
  const getLayout = Component.getLayout || ((page) => page)

  return getLayout(<Component {...pageProps} />)
}

CodePudding user response:

This is, unfortunately, one of the pitfalls of NextJS. The community cannot seem to agree on a singular approach to shared state and layout management.

My company and I managed to get around this using a custom app component. Though you will see (as @rantao pointed out), you can also use a layout.

/* _app.js */
export default function _App({ Component, pageProps }){
    const navigationEnabled = Component?.navigation ?? true;
    const footerEnabled = Component?.footer ?? true;

    // Just an example. You don't have to have these exact components or layout.
    return <>
        { navigationEnabled === true && <Navigation />}
        <Component {...pageProps />
        { footerEnabled === true && <Footer />}
    </>;
}

/* page.js */
export default function Page(){}
// Hide the navigation of this page. 
Page.navigation = false; 
  • Related