So, I\'m using the gatsby-mdx plugin to create a site from MDX files. I want to create an association between the SitePage object and the Mdx object so that I can do one gra
So I finally found a better solution (than my previous attempt, which involves pumping mdx node into page’s context
).
Gatsby has a undocumented method to link nodes to one another:
Yes, you can can use createNodeField with the not-yet-documented ___NODE syntax to create links between nodes.
So, the steps are like this:
createPage
, store the id
of the Mdx node to SitePage node.onCreateNode
, if node is SitePage
, use createNodeField
with the Mdx___NODE
as field name and Mdx node's id as value.My gatsby-node.js
:
const path = require("path")
const { createFilePath } = require("gatsby-source-filesystem")
exports.onCreateNode = ({ node, actions, getNode }) => {
const { createNodeField } = actions
if (node.internal.type === "SitePage" && node.context && node.context.id) {
createNodeField({
name: "Mdx___NODE",
value: node.context.id,
node,
})
}
if (node.internal.type === "Mdx") {
const value = createFilePath({ node, getNode })
createNodeField({
// 1) this is the name of the field you are adding,
name: "slug",
// 2) this node refers to each individual MDX
node,
value: `/blog${value}`
})
}
}
exports.createPages = async ({ graphql, actions }) => {
const { createPage } = actions;
const { data, errors } = await graphql(`
{
allMdx {
edges {
node {
id
fields {
slug
}
}
}
}
}
`)
if (errors) throw errors
data.allMdx.edges.forEach(({ node }) => {
createPage({
path: node.fields.slug,
component: path.resolve(`./src/components/posts-page-layout.js`),
context: { id: node.id }
});
});
};
Result:
Hope it helps!