Search code examples
graphqlgatsbycontentful

Rendering rich text with Gatsbyjs and Contentful using gatsby-source-contentful


I'm using gatsby-source-contentful v4.6.4

According to the docs, I should be able to use a query similar to the following without issue (simplified query from the docs):

query MyQuery {
  contentfulBlogPost {
        id
        bodyRichText {
             raw
        }
    }
 }

Along with documentToReactComponents. However, the following code doesn't throw an error, but simply doesn't parse the rich text:

function ArticleBody({raw}) {

return (
<>
    {
        raw.map(rtNode => {
            return (
                <>
                    {documentToReactComponents(rtNode)}
                </>
            )
        })
    }
</>
);
}

export default ArticleBody;

Solution

  • The problem was that I needed to parse the JSON, and step down the object into the content array.

    Here's the component:

    function ArticleBody({raw}) {
    
    return (
        <>
            {
                JSON.parse(raw).content.map(rtNode => {
                    return (
                        <>
                            {documentToReactComponents(rtNode)}
                        </>
                    )
                })
            }
        </>
    );
    }
    
    export default ArticleBody;
    

    And here's the GraphQL query:

    query{
              allContentfulBlog {
                edges {
                  node {
                    id
                    blogPost {
                      raw
                    }
                  }
                }
              }
           }