šŸ‘‹ Next.js Conf 2024: Come build, party, run, and connect with us! See all events

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?