Skip to main content
0.78.0
View Zag.js on Github
Join the Discord server

Collection

The Collection class is designed to manage a collection of items, providing functionalities such as sorting, searching, getting next or previous items, converting items to values or strings, checking if an item is disabled, and more.

Good to know: This is used in the select and combobox components

List Collection

A list collection is a collection that is based on an array of items. It is created by passing an array of items to the constructor.

import { ListCollection } from "@zag-js/collection" const collection = new ListCollection({ items: [ { label: "Apple", value: "apple" }, { label: "Banana", value: "banana" }, ], })

Converting value to item

You can convert a value to an item by passing the value to the find or findMany method.

const item = collection.find("banana") console.log(item) // { label: "Banana", value: "banana" } const items = collection.findMany(["apple", "banana"]) console.log(items) // [{ label: "Apple", value: "apple" }, { label: "Banana", value: "banana" }]

Value Traversal

You can get the next or previous item based on a value by passing the value to the getNextValue or getPreviousValue method.

const nextValue = collection.getNextValue("apple") console.log(nextValue) // banana const previousItem = collection.getPreviousValue("banana") console.log(previousItem) // apple

Likewise, you can also get the first or last item by calling the firstValue or lastValue computed properties.

console.log(collection.firstValue) // apple console.log(collection.lastValue) // banana

Check for value existence

You can check if a value exists in the collection by calling the has method.

const hasValue = collection.has("apple") console.log(hasValue) // true

Working with custom objects

If you are working with custom objects, you can pass a function to the itemToString and getItemValue options to specify how to convert an item to a string and a value, respectively.

import { ListCollection } from "@zag-js/collection" const collection = new ListCollection({ items: [ { id: 1, name: "apple" }, { id: 2, name: "banana" }, { id: 3, name: "cherry" }, ], itemToString: (item) => item.name, itemToValue: (item) => item.id, })

To disable an item, you can pass a function to the isItemDisabled option.

import { ListCollection } from "@zag-js/collection" const collection = new ListCollection({ items: [ { id: 1, name: "apple" }, { id: 2, name: "banana" }, { id: 3, name: "cherry" }, ], isItemDisabled: (item) => item.id === 2, })

Reorder items

You can reorder items by calling the reorder method and passing the starting index and the ending index of the item to be moved.

const fromIndex = 1 // Banana const toIndex = 0 // Apple collection.reorder(fromIndex, toIndex) console.log(collection.items) // [{ label: "Banana", value: "banana" }, { label: "Apple", value: "apple" }]

Edit this page on GitHub

Proudly made in🇳🇬by Segun Adebayo

Copyright © 2024
On this page