Search code examples
reactjsgatsbycontentful

Gatsby Source Contentful 4.x - Rich Text - changes to JSON


I'm trying to get the Rich Text from Contentful, but in the 4.x version of gatsby-source-contentful, the documentation no longer seems updated. It refers to the json, but it has changed to raw, which means I don't know how to proceed.

This is my code:

import React from "react"
import { graphql, Link } from "gatsby"
import { documentToReactComponents } from "@contentful/rich-text-react-renderer"

import Layout from "../components/layout/layout"
import Img from "gatsby-image"
import SEO from "../components/layout/seo"

export const query = graphql`
  query($slug: String!) {
    contentfulBlogPost(slug: { eq: $slug }) {
      title
      publishedDate(formatString: "Do MMMM, YYYY")
      featuredImage {
        fluid(maxWidth: 750) {
          ...GatsbyContentfulFluid
        }
      }
      body {
        json
      }
    }
  }
`

const BlogPost = props => {
  const options = {
    renderNode: {
      "embedded-asset-block": node => {
        const alt = node.data.target.fields.title["en-US"]
        const url = node.data.target.fields.file["en-US"].url
        return <img alt={alt} src={url} />
      },
    },
  }

  return (
    <Layout>
      <SEO title={props.data.contentfulBlogPost.title} />
      <Link to="/blog/">Visit the Blog Page</Link>
      <div className="content">
        ...
        {props.data.contentfulBlogPost.featuredImage && (
          <Img
            className="featured"
            fluid={props.data.contentfulBlogPost.featuredImage.fluid}
            alt={props.data.contentfulBlogPost.title}
          />
        )}
        {documentToReactComponents(
          props.data.contentfulBlogPost.body.json,
          options
        )}
      </div>
    </Layout>
  )
}

export default BlogPost

If you have a look at the section below, this is where it gets wrong I believe. The error message I'm getting is "Cannot query field "json" on type "ContentfulBlogPostBody".", but if I changes it to raw instead of json, it doesn't give me any errors, but then it doesn't display the rich text (body):

 }
      body {
        json
      }
    }
  }
`

Below is a screenshot of how the content model is setup at Contentful:

Contentful - Content Model

How do I use the newer version of gatsby-source-contentful (currently on version 4.2.1) with the change in how it handles the rich text?


Solution

  • You can find an example of how to use raw in the documentation for gatsby-source-contentful.

    This is how a query could look like using richtext:

    {
      allContentfulBlogPost {
        edges {
          node {
            bodyRichText {
              raw
              references {
                ... on ContentfulAsset {
                  contentful_id
                  __typename
                  fixed(width: 1600) {
                    width
                    height
                    src
                    srcSet
                  }
                }
                ... on ContentfulBlogPost {
                  contentful_id
                  __typename
                  title
                  slug
                }
              }
            }
          }
        }
      }
    }
    

    And you can use it like so.

    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>
            </>
          )
        },
      },
    }
    
    function BlogPostTemplate({ data, pageContext }) {
      const { bodyRichText } = data.contentfulBlogPost
    
      return <div>{bodyRichText && renderRichText(bodyRichText, options)}</div>
    }