Go Behind the Experience to see how Tecovas brings the West to life with Sanity 🤠 July 18th

How to get the number of nested/children components in a GROQ query.

3 replies
Last updated: Jan 19, 2024
hello all 👋 I have the following GROQ: I’m retrieving a list of components as ‘items’. Now I need the number of nested/children components each parent component has. How can I get the number of each component’s children/subpages? I was trying to obtain this number inside ‘children’.

{
            template,
            layout_library {
                hero_title,
                components_section_title,
                'items': *[_type == 'components' && layout_components.is_parent == true] | order(title asc){
                    title,
                    _id,
                    slug,
                    layout_components {
                      component_image${imageQuery},
                    }
                },
                'children': *[_type == 'components' && layout_components.is_parent == false] | order(title asc){
                    ???
                },
            },
        }
Jan 18, 2024, 6:20 PM
'children': *[count(_type == 'components' && layout_components.is_parent == false)]
Jan 18, 2024, 6:46 PM
thanks
user E
! but this wouldn’t work as I don’t need just one number.
Let me explain this a little bit more. I’ve got a Library page for a Design system where I’m looping main components like Button and Accordion. Button has 3 types of buttons/subpages: button/button-01, button/button-02 and button/button-03.

In Library, I’m looping the components that are parent pages and show the info of them. In this case the title for Button and a description. And then, just under the the description it says “3 button types available”. how do I get the 3 for button, the X for accordion and other numbers for other components?
Jan 19, 2024, 8:58 AM
fixed it this way:
'items': *[_type == 'components' && layout_components.is_parent == true] | order(title asc){
                    title,
                    _id,
                    slug,
                    'total': count(*[_type == 'components' && parent_component == ^.slug.current]),
                    
                },
Jan 19, 2024, 9:52 AM

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?