Issue with rendering a blockContent element nested inside an array in Gatsby
When working with blockContent (Portable Text) nested inside an array in Sanity with Gatsby, you're running into a common pattern where the _raw fields work differently than you might expect. Here's how to handle this:
Understanding _raw Fields with Nested Arrays
The gatsby-source-sanity plugin generates _raw fields only for top-level document fields, not for fields nested within arrays or objects. As you've discovered, when you have blockContent inside an array, you won't get individual _rawFieldName fields for those nested items.
Solution: Access via Parent _raw Field
Instead of looking for _rawBlockContent on individual array items, you need to:
- Query the parent array's
_rawfield - For instance, if your array field is calledsections, query_rawSections - Use
resolveReferencesto expand any references within that raw data
Here's an example query structure:
query MyPageQuery {
sanityPage {
sections {
# Regular fields work fine here
_key
_type
}
# Access the raw blockContent through the parent array's _raw field
_rawSections(resolveReferences: {maxDepth: 5})
}
}Working with the Data
In your component, you'd then access the blockContent like this:
const Page = ({ data }) => {
const { sections, _rawSections } = data.sanityPage
return (
<>
{_rawSections?.map((section, index) => {
// Now you have access to the full raw blockContent
if (section._type === 'textSection' && section.content) {
return (
<PortableText
key={section._key}
value={section.content} // This is your blockContent
/>
)
}
return null
})}
</>
)
}Key Points
- "For instance, a field named
bodywill be mapped to_rawBody" - but this only applies to document-level fields, not nested ones - The
resolveReferencesparameter withmaxDepthhelps expand any referenced documents within your blockContent - You access nested blockContent through the parent field's
_rawversion (like_rawSectionsfor asectionsarray) - The entire array structure is preserved in the
_rawfield, including all nested blockContent
This is the intended behavior of the plugin - raw fields are generated at the document root level to avoid excessive complexity in the GraphQL schema. By querying the parent array's _raw field, you get the complete nested structure including your blockContent elements.
Sanity – Build the way you think, not the way your CMS thinks
Sanity is the developer-first content operating system that gives you complete control. Schema-as-code, GROQ queries, and real-time APIs mean no more workarounds or waiting for deployments. Free to start, scale as you grow.