Gatsby
Up and Running with Gatsby: Markdown & MDX

Extracting a Default Layout

PRO

We can pull our custom layout into its own file as a default layout.

In the last video, we added a layout for our "Things to Do" page. It'd be better if we didn't have to change that layout in every page, though. Let's create a default layout instead.

First, from thingstodo.mdx, cut the layout code we made:

import Layout from "../components/Layout.js"

export default ({ children }) => <Layout>{children}</Layout>

Create a new file under src/pages called markdownpage-template.js and paste it in there. You'll need to import React at the top:

import React from "react"

To get Gatsby to use this component as our default page for MDX, we need to update gatsby-config.js. We can change our entry for gatsby-plugin-mdx into an object and add an options object. This object will include an extensions array and a defaultLayouts object. It will look like this:

// gatsby-config.js
{
      resolve: `gatsby-plugin-mdx`,
      options: {
        extensions: [`.mdx`, `.md`],
        defaultLayouts: {
          default: require.resolve("./src/pages/markdownpage-template.js"),
        },
      },
    },

Notice that we're now telling the MDX plugin to use that template we created as the default layout for all MDX pages.

Restart the server and you should still see the "Things to Do" route working correctly!