There are two most common ways of using markdown in Gatsby with a headless CMS tool.
This post will present how to use them with Contentful service. Additionally it will include contenful image converter inside markdown.
Amazing plugin for converting and optimaizing images from contentful into Gatsby blog.
$ npm install gatsby-remark-images-contentful
This is a very popular plugin mostly used for processing markdown and them placing it into the HTML. It is also usefull if you want not only process markdown but also include your own JSX components.
$ npm install gatsby-plugin-mdx @mdx-js/mdx @mdx-js/react
module.exports = {
plugins: [
{
resolve: `gatsby-plugin-mdx`,
options: {
gatsbyRemarkPlugins: [
{
resolve: `gatsby-remark-images-contentful`,
options: {
maxWidth: 590,
linkImagesToOriginal: false,
withWebp: true,
loading: "lazy",
},
},
],
},
},
]
}
export const query = graphql`
contentfulBlogPost(slug: { eq: $slug }) {
title
body {
childMdx {
body
}
}
}
`
import React from "react"
import MDXRenderer from "gatsby-plugin-mdx/mdx-renderer"
import { MDXProvider } from "@mdx-js/react"
const BlogPostTemplate = ({data}) => {
const blogData = data.contentfulBlogPos
return (
<MDXProvider>
<h1>{blogData.title}</h1>
<article className={classes.article}>
<MDXRenderer>{blogData.body.childMdx.body}</MDXRenderer>
</article
</MDXProvider>
)
}
Plugin powered by remark processor. It parses markdown but without included parser for React components.
npm install --save gatsby-transformer-remark
module.exports = {
plugins: [
{
resolve: `gatsby-transformer-remark`,
options: {
plugins: [
{
resolve: `gatsby-remark-images-contentful`,
options: {
maxWidth: 590,
linkImagesToOriginal: false,
withWebp: true,
loading: "lazy",
},
},
],
},
},
]
}
Add markdown field in Contentful Content Type of your blog as in previous plugin description
In your blog post template graphql query get markdown body
export const query = graphql`
contentfulBlogPost(slug: { eq: $slug }) {
title
body {
childMarkdownRemark {
html
}
}
}
`
import React from "react"
import MDXRenderer from "gatsby-plugin-mdx/mdx-renderer"
import { MDXProvider } from "@mdx-js/react"
const BlogPostTemplate = ({data}) => {
const blogData = data.contentfulBlogPos
return (
<>
<h1>{blogData.title}</h1>
<div
dangerouslySetInnerHTML={{
__html: blogData.body.childMarkdownRemark.html,
}}
></div>
</>
)
It is your choice which plugin you will use. I have tried both and currenly I’m using gatsby-plugin-mdx for markdown processor including custom component.
I’m also very happy with plugin for simple image optimization gatsby-remark-images-contentful. If you are looking for low cost and simple image optimalization for your blog, this is it!