Was this page helpful?

Using Rich Text with Gatsby

Using Rich Text with the Contentful Source plugin

Before using Rich Text with Gatsby you have to install the Contentful Source plugin first. Once you have done that you can query Rich Text content with the following GraphQL query:

query {
  allContentfulBlogPost {
    edges {
      node {
        bodyRichText {
          json
        }
      }
    }
  }
}

This returns a JSON object which follows the Rich Text Abstract Syntax Tree.

Using the Rich Text rendering libraries to render the content

After getting the response object, it's easy to customize it by using the Contentful supported React Renderer.

Here's an example of how apply rendering options in a Gatsby view file:

import { BLOCKS, MARKS } from "@contentful/rich-text-types"
import { documentToReactComponents } from "@contentful/rich-text-react-renderer"

const Bold = ({ children }) => <span className="bold">{children}</span>
const Text = ({ children }) => <p className="align-center">{children}</p>

const options = {
  renderMark: {
    [MARKS.BOLD]: text => <Bold>{text}</Bold>,
  },
  renderNode: {
    [BLOCKS.PARAGRAPH]: (node, children) => <Text>{children}</Text>,
  },
}

documentToReactComponents(node.bodyRichText.json, options)

One piece of caution here is that in previous libraries of Rich Text rendering in Gatsby, the above customization happened in gatsby-config.js. This is not the case anymore as you can customize how Rich Text renders in a template from within the template file (.jsx) itself.