Having a consistent layout throughout your website can greatly improve user experience. One way to achieve this is by using a wrapper component that includes common elements like a sidebar or header. In this blog post, we will explore two approaches to implementing a wrapper component in Next.js.
Approach 1: Using a Higher Order Component (HOC)
The first approach involves creating a Higher Order Component (HOC) called Layout.js
, which can be used to wrap other components. Here’s an example implementation of the Layout.js
component:
export default Page => {
return () => (
<div>
<nav>
<ul>...</ul>
</nav>
<main>
<Page />
</main>
</div>
)
}
With this HOC, you can import separate components for the heading and sidebar, and include any required CSS styles. To use the Layout.js
component in your pages, you can do the following:
import withLayout from '../components/Layout.js'
const Page = () => <p>Here's a page!</p>
export default withLayout(Page)
While this approach works well for simple cases, it has limitations when it comes to using the getInitialProps()
lifecycle method on a page component. Since the HOC is used to wrap the main page component, getInitialProps()
will not be called on the page component itself. Instead, it will be called on the HOC component. This can complicate the logic if you rely on getInitialProps()
in your pages.
Approach 2: Using Props
To overcome the limitations of the HOC approach, you can use props to pass the content to the wrapper component. Here’s an example implementation of a wrapper component using props:
export default props => (
<div>
<nav>
<ul>...</ul>
</nav>
<main>
{props.content}
</main>
</div>
)
In your pages, you can use the wrapper component like this:
import Layout from '../components/Layout.js'
const Page = () => (
<Layout content={(
<p>Here's a page!</p>
)} />
)
This approach allows you to still use the getInitialProps()
lifecycle method within your page component. The only downside is that you need to write the component JSX inside the content
prop.
import Layout from '../components/Layout.js'
const Page = () => (
<Layout content={(
<p>Here's a page!</p>
)} />
)
Page.getInitialProps = ({ query }) => {
//...
}
By choosing the appropriate approach based on your project requirements, you can easily add a wrapper component to your Next.js app and create a consistent layout across your pages.