💾Collection

Use Collection to iterate over data and repeat the same structure but with different data for each iteration.

Why Collections are needed

Let's say you are building a list of all your blog posts. Each blog post will have an image, a title, and a link.

You have 50 blog posts. Does this mean you need to duplicate your design 50 times manually? No.

Collections let you design something once, and it will repeat it for every item in the array and contain the data for the current iteration (e.g., the blog post title).

What's an array?

An array is a programming term that generally translates to a list of data.

In the case of blog posts, this might look like the following:

0 { title: "Hello world"},
1 { title: "Lorem ipsum"},
2 { title: "Webstudio rocks!" }

It's important that when binding data to a Collection, you must bind the array, i.e., the data you want to iterate over. If you don't bind the array, you'll receive an error: "The Collection component requires an array in the data property. When binding external data, it is likely that the array is nested somewhere within, and you need to provide the correct path in the binding."

If you are binding external data, the array is nested somewhere within.

In the image, the data bound to the component is:

  1. ❌ Not the array

  2. ❌ The first item in the array (0), not the entire list

  3. ✅ The array

It's unclear why each item is correct or incorrect by just looking at the image, so let's clarify.

You'll know when you get to the array when the next items in the autocomplete are numbers. The numbers represent each item in the list. Once you see the numbers, backspace, as you don't want to select one item; you want the list.

How to use Collection

Add the Collection component to the canvas and either manually enter data (less common) or bind data to it (more common).

The Collection iterates over the array, so you must bind just the array portion of your variable to it. See What's an Array for more info.

Optionally, rename the default Collection Item variable to something more semantic. If you are iterating over blog posts, name it "Blog Post."

Now, you can add components to the Collection, and the Collection will automatically duplicate it for the number of items in the array. If you have multiple components, wrap everything in a Box component.

Next, bind the Collection Item (or whatever you named it) to the various components. You will see it output a different value depending on the iteration.

Last updated