NextJS Examples | Layout

Last modified: October 12, 2019

NextJS Examples | Starter

NextJS Examples | Layout

NextJS Examples | Express

NextJS Examples | MongoDB

Using layouts, you can easily create reusable templates for different pages...

In the components/ folder, create a new file MyLayout.js

import Nav from './nav'

const MyLayout = props => (
  <div>
    <Nav />
    <div>
      {props.children}
    </div>
  </div>
)

export default MyLayout

then in the pages/ directory you can reference MyLayout like this...

import React from 'react'
import Head from 'next/head'
import Nav from '../components/nav'
import MyLayout from '../components/MyLayout'

const Home = () => (
  <MyLayout>
    <Head>
      <title>Home</title>
    </Head>
    hello
  </MyLayout>
)

export default Home

Notice how we include a <Nav/> in our MyLayout component. By wrapping our Home component in <MyLayout> tags, we don't have to include <Nav/> with every page. Instead, we use a common MyLayout across different pages.

Notice the reference to {props.children} from the MyLayout component. This represents all child content that will be displayed in between the <MyLayout> tags.

You can also create a layout like this...

import Nav from './nav';

const withLayout = Page => {
  return () => (
    <div>
      <Nav />
      <Page />
    </div>
  );
};

export default withLayout;

and then in your pages/ file...

import withLayout from '../components/MyLayout';
const PageContent = () => <p>Content for my layout!</p>;
export default withLayout(PageContent);

The main difference with this approach is that we are treating the page content as input to a function.

Yet another approach to creating layouts...

import Nav from './nav';
const MyLayout = props => (
  <div>
    <Nav />
    {props.content}
  </div>
);

export default MyLayout;

and then in your pages/ file...

import MyLayout from '../components/MyLayout.js';

const pageContent = <p>Hello Next.js</p>;

export default function Index() {
  return <MyLayout content={pageContent} />;
}

This approach is similar to the previous example in that we are passing the pageContent into our MyLayout component. The main difference is that we are passing the contents as props rather than a function param.

All of these examples are valid approaches to implementing sharable components in NextJS.

You might also like: