Hey DatoCMS crew!
Context
Iām migrating from Modular Content Fields to Structured Text Fields for my Gatsby blog, using the example Github repo as my guide.
Goal
To render different blocks used within a Structured Text Field.
The two different blocks are as follows
- Image: returns
<GatsbyImage src={record.image.gatsbyImageData}/>
- External Embed: returns
<div>{record.video.url}</div>
Problem
When viewing one of my blog posts with just text and image blocks, everything works. However, when I view a blog post with text, image and external embed blocks, the following error occurs.
One unhandled runtime error found in your files. See the list below to fix it:
Error in function renderBlock in ./src/components/post-body.tsx:15
record.image is null
Here are the contents of post-body
minus the imports.
export default function PostBody({ content }) {
return (
<section className="post">
<StructuredText
data={content}
renderBlock={({ record }) => {
switch (record.__typename) {
case "DatoCmsVisual":
return (
<div className="post__visual">
<GatsbyImage image={record.image.gatsbyImageData} />
</div>
)
case "DatoCmsExternalEmbed":
return <div className="post__visual">{record.externalVideo.url}</div>
default:
return (
<>
<p>Don't know how to render a block!</p>
<pre>{JSON.stringify(record, null, 2)}</pre>
</>
)
}
}}
/>
</section>
)
}
I suspect the PostBody
function isnāt the problem here, rather my lack of understanding how to query multiple blocks within Structured Text. Here is the query which I use to render the contents of each post.
export const pageQuery = graphql`
query ($slug: String!) {
site: datoCmsSite {
favicon: faviconMetaTags {
...GatsbyDatoCmsFaviconMetaTags
}
}
post: datoCmsPostNext(slug: { eq: $slug }) {
coverImage {
alt
gatsbyImageData(width: 1500)
}
title
summary
date(formatString: "MMMM DD, YYYY")
content {
value
blocks {
__typename
id: originalId
image {
alt
gatsbyImageData(width: 1500)
}
externalVideo {
src
}
}
}
slug
seo: seoMetaTags {
...GatsbyDatoCmsSeoMetaTags
}
}
}
`
I suspect this is something basic, but any help would be greatly appreciated.