Was this page helpful?

Using Rich Text with the Contentful Source plugin

Before using Rich Text with the popular React.js Framework 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 {
          raw
          references {
            ... on ContentfulAsset {
              contentful_id
              fixed(width: 1600) {
                width
                height
                src
                srcSet
              }
            }
            ... on ContentfulBlogPost {
              contentful_id
              title
              slug
            }
          }
        }
      }
    }
  }
}

This query returns a string representing the JSON object which follows the Rich Text Abstract Syntax Tree and a list of references found within the Rich Text content. ​

Using the Rich Text rendering libraries to render the content

After getting the response object and the references, it's easy to customize it by using the Contentful supported Richtext 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 { renderRichText } from "gatsby-source-contentful/rich-text"
​
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>,
    [BLOCKS.EMBEDDED_ASSET]: node => {
      return (
        <>
          <h2>Embedded Asset</h2>
          <pre>
            <code>{JSON.stringify(node, null, 2)}</code>
          </pre>
        </>
      )
    },
  },
}
​
renderRichText(node.bodyRichText, options)

Note: Be aware that previous versions of the Gatsby Contentful source plugin used a json field. This got replaced with raw to give you more flexibility in rendering and to fix performance issues.