In this post, we will be looking into how to create pages programmatically using MDX in Gatsby.
To get up and running, we need to install a couple of plugins
npm i gatsby-plugin-mdx @mdx-js/mdx @mdx-js/react
Then we need to configure gatsby-plugin-mdx inside gatsby-config.js
plugins: [
{
resolve: 'gatsby-plugin-mdx',
options: {
defaultLayouts: {
default: require.resolve('./src/components/Layout.js'),
},
},
},
];
So first, we need to resolve the plugin gatsby-plugin-mdx
because we also want to pass in options object which defines what layout that we want to use in our MDX files.
Note: require.resolve
give us the absolute path name.
As a result, any MDX files that we load will be loaded into the Layout.js template that we defined in the gatsby-config
.
Now that we have installed the plugin, it will look for mdx files in the pages or posts directory which we defined in gatsby-config.
To get the post pages into gatsby, we are going to use another plugin gatsby-source-filesystem
npm i gatsby-source-filesystem
To get them to the data layer so that we can access them. The gatsby source file system is a way to use local files as part of the graphql data layer.
Once it gets installed, we need to update gatsby config to resolve source filesystem plugin
plugins: [
{
resolve: 'gatsby-plugin-mdx',
options: {
defaultLayouts: {
default: require.resolve('./src/components/Layout.js'),
},
},
},
{
resolve: 'gatsby-source-filesystem',
options: {
name: 'posts',
path: `${__dirname}/content/posts`,
},
},
];
As a result, it will load anything that it finds in the path /content/posts
as part of the data layer, and because we have gatsby MDX plugin installed it’s going to look for MDX files and transform those into GraphQL nodes.
The whole reason for using MDX is because we want to add some sort of interactivity in the markup generated pages.
#graphql #gatsbyjs #reactjs #react #programming