Add a wrapper component to your Next.js application

How to use the wrapper component and add a public sidebar or header to it

All pages on your website look roughly the same. There is a chrome layer, a general base layer, you just want to change the content.

There is a navigation bar, a sidebar, and then the actual content.

How do you build such a system in Next.js?

There are two ways. One is in useHigher order components, By creating acomponents/Layout.jsingredient:

export default Page => {
  return () => (
    <div>
      <nav>
        <ul>....</ul>
      </nav>
      <main>
        <Page />
      </main>
    </div>
  )
}

Here, we can import separate components for the title and/or sidebar, and we can also add all the CSS we need.

You can use it in every page as follows:

import withLayout from '../components/Layout.js'

const Page = () => <p>Heres a page!</p>

export default withLayout(Page)

But I found this only works in simple cases, you don’t need to callgetInitialProps()On the page.

why?

becausegetInitialProps()Only called on page components. However, if we export the higher-order components of withLayout() from the page,Page.getInitialProps()Is not called.withLayout.getInitialProps()will.

To avoid unnecessarily complicating our code base, the alternative is to use props:

export default props => (
  <div>
    <nav>
      <ul>....</ul>
    </nav>
    <main>
      {props.content}
    </main>
  </div>
)

Now in our page, we use it like this:

import Layout from '../components/Layout.js'

const Page = () => ( <Layout content={( <p>Heres a page!</p> )} /> )

This method lets us usegetInitialProps()Starting from the inside of our page component, the only drawback is that it must becontentpillar:

import Layout from '../components/Layout.js'

const Page = () => ( <Layout content={( <p>Heres a page!</p> )} /> )

Page.getInitialProps = ({ query }) => { //… }

Download mine for freeNext.js manual


More tutorials next: