Once you have gatsby-plugin-mdx
available, either through Gatsby’s own MDX starter or by installing it into an existing Gatsby site, any MDX files located within Gatsby’s src/pages directory will automatically be converted into pages. For instance, if you create a page src/pages/about.mdx, Gatsby renders it at my-site.com/about.
You can use frontmatter in Markdown to define certain fields that will be available in Gatsby’s GraphQL API as well through the allMdx
root field. For example, suppose you have an MDX file with the following frontmatter:
---
title: Hello MDX!
date: 2021-04-19
---
#
Hello MDX!
You can query for this frontmatter material by issuing the following GraphQL query either in GraphiQL or any in other file in your Gatsby site that supports GraphQL queries:
query {
allMdx {
edges {
node {
frontmatter {
title
date(formatString: "MMMM DD, YYYY")
}
}
}
}
}
If your Markdown document is located in your src/pages directory and not programmatically generated, you can also export the query directly within the document itself, if you wish to have your GraphQL query and Markdown located in the same file:
---
title: Hello MDX!
date: 2021-04-19
---
import { graphql } from "gatsby"
#
Hello MDX!
export const pageQuery = graphql`
query {
allMdx {
edges {
node {
frontmatter {
title
date(formatString: "MMMM DD, YYYY")
}
}
}
}
}
`
WARNING
In MDX files, frontmatter must precede import
statements referring to outside React components.
MDX also makes available frontmatter within your MDX file itself, meaning you can reference frontmatter fields within JSX elements from inside the MDX document, as follows:
---
title: Hello MDX!
date: 2021-04-19
---
#
Hello MDX!
<ul>
<li>Title: {props.pageContext.frontmatter.title}</li>
<li>Date: {props.pageContext.frontmatter.date}</li>
</ul>
Leave a Reply