Retrieve Nested Categories in Storefront
In this guide, you'll learn how to retrieve nested categories in the storefront.
How to Retrieve Nested Categories in Storefront?#
A product category has parent and child categories. For example, a "Shoes" category can have a "Running Shoes" child category.
There are two ways to retrieve nested categories:
- Retrieve nested categories of a category. This is useful if you're showing the nested categories on a category page.
- Retrieve all categories as a hierarchy. This is useful if you're showing the categories in a tree structure, such as in a menu or navigation bar.
Retrieve Nested Categories of a Category#
To retrieve the child or nested categories of a category in your storefront, pass to the Get a Category API Route the following query parameters:
include_descendants_tree=true
to retrieve each category's nested categories at all levels.- Add
category_children
tofields
, which is the field that will hold a category's nested categories.- You can either pass
*category_children
to retrieve all fields of a child category, or specify the fields specifically to avoid a large response size. For example,field=category_children.id,category_children.name
.
- You can either pass
For example:
In this example, you retrieve the nested categories of a category by passing the include_descendants_tree
query parameter to the Get a Category API Route.
The response has a product_category
field, which is a product category object. It will have a category_children
field, which is an array of product category objects.
Then, in the React component, you show a category's children by iterating over the category_children
field.
Retrieve Categories as a Hierarchy#
Alternatively, you may want to retrieve all categories as a hierarchy.
To do this, you can pass the include_descendants_tree
query parameter to the List Product Categories API Route, along with the parent_category_id
query parameter set to null
. This ensures that only categories with children are retrieved at the top level.
For example:
In this example, you retrieve all categories as a hierarchy by passing the include_descendants_tree
query parameter to the List Product Categories API Route.
The response has a product_categories
field, which is an array of product category objects.
Each category will have a category_children
field, which is an array of product category objects.
You can then show the categories in a tree structure by iterating over the product_categories
field and displaying the category_children
field for each category.