SOURCING FROM CONTENTFUL

Sourcing from contentful

I thought it would be easier to source from contentful than it was, but all of the guides (both at contentfuls website and gatsbys website) was out of date. I did not receive a rich text body from which I could parse inside the graphQL layer. I needed to do that in Gatsby with JSON.parse.

What they said

Query

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

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

const  = ({ children }) => <span className="bold">{children}</span>
const  = ({ 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)

What I did

Query

query($slug: String!) {
  contentfulPost(slug: { eq: $slug }) {
    publishDate
    slug
    title
    content {
      raw
    }
  }
}

Gatsby

const post = data.contentfulPost
const markdown = JSON.parse(post.content.raw)
return (
  <PageStructure
    pageTitle={post.title}
    metaContent={`Blog post describing an event or day`}
  >
    <Box>{markdown && documentToReactComponents(markdown, options)}</Box>
  </PageStructure>
)

[email protected]
© 2020-2022
André Åström [kjof]