๐Ÿ”ฎ Sanity Create is here. Writing is reinvented. Try now, no developer setup

How to fetch and render specific components from a document using groq and PortableText in the frontend.

12 replies
Last updated: Dec 21, 2022
Hello! I have this schema in a document:
 {
         title: 'Block Content',
         name: 'blockContent',
         type: 'array',
         of: [{type: 'hero'}, {type: 'platforms'}]
        }
I would like to know, how can I fetch for example
hero
or
platforms
of this document using groq in the frontend!?
Dec 21, 2022, 2:47 PM
Hey
user B
! To clarify, are you trying to extract these blocks out your block content array without the rest of the content?
Dec 21, 2022, 6:17 PM
Yes
user M
I wanted to extract components data separately,
Dec 21, 2022, 6:18 PM
like
hero
, or
platforms
Dec 21, 2022, 6:19 PM
user M
Any idea? ๐Ÿ˜„
Dec 21, 2022, 6:41 PM
There are a ton of support requests, so it'll take me a bit to put together. I'll probably have it by the end of my day ๐Ÿ™‚
Dec 21, 2022, 6:42 PM
user M
, Can I use directly PortableText to handle the block contents ?
Dec 21, 2022, 6:46 PM
Are you trying to render them inside of PortableText component or on their own? Just want to make sure I understand.
Dec 21, 2022, 6:48 PM
Initially these components must be rendered inside of Portable Text but I ambit confused of how it works
Dec 21, 2022, 6:50 PM
What I want exactly is to display components such as Hero, Header, Footer using the portable text
Dec 21, 2022, 7:11 PM
    const main = await sanity.fetch(groq
    `
      *[_type == "homepage" ][1]{
        blockContent[_type == "hero"][0]
      }
    `
    )
This will return the document with the specified component:
hero
. But when dealing with PortableText:
<PortableText value={props.main} components={ptComponents} />
I get this error:

 Unknown block type "undefined", specify a component for it in the `components.types` prop
This is the
ptComponents

const ptComponents = {
    // Components for totally custom types outside the scope of Portable Text
    types: {
        hero: Main,
    },
  
    // Overrides for specific block styles - in this case just the `h2` style
    block: {
     
    },
  
    // Implements a custom component to handle the `schnauzer` list item type
    list: {
     
    },
  
    // Custom components for marks - note that `link` overrides the default component,
    // while the others define components for totally custom types.
    marks: {

    },
  }

Dec 21, 2022, 7:36 PM
Main
is a UI component in the frontend
Dec 21, 2022, 7:36 PM
Ah dont bother
user M
I found a solution! Thanks.
Dec 21, 2022, 7:47 PM

Sanityโ€“ build remarkable experiences at scale

Sanity is a modern headless CMS that treats content as data to power your digital business. Free to get started, and pay-as-you-go on all plans.

Was this answer helpful?