리스트 컬렉션(List Collection)
리스트 컬렉션은 항목 배열을 기반으로 하는 컬렉션이에요. 생성자에 항목 배열을 전달해 만들 수 있어요.
출처: 문서
본문
리스트 컬렉션은 항목 배열을 기반으로 하는 컬렉션이에요. 생성자에 항목 배열을 전달해 만들어요.
import { createListCollection } from '@ark-ui/react/collection'
const collection = createListCollection({
items: [
{ label: 'Apple', value: 'apple' },
{ label: 'Banana', value: 'banana' },
],
})
console.log(collection.items) // [{ label: 'Apple', value: 'apple' }, { label: 'Banana', value: 'banana' }]
값을 항목으로 변환(Converting value to item)
find 또는 findMany 메서드를 사용해 값을 항목으로 변환해요.
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)
getNextValue 또는 getPreviousValue 메서드를 사용해 값 기준으로 다음 또는 이전 항목을 얻어요.
const nextValue = collection.getNextValue('apple')
console.log(nextValue) // banana
const previousItem = collection.getPreviousValue('banana')
console.log(previousItem) // apple
마찬가지로 firstValue 또는 lastValue 계산된 속성을 사용해 첫 번째 또는 마지막 항목을 얻어요.
console.log(collection.firstValue) // apple
console.log(collection.lastValue) // banana
값 존재 확인(Check for value existence)
has 메서드를 사용해 컬렉션에 값이 존재하는지 확인해요.
const hasValue = collection.has('apple')
console.log(hasValue) // true
커스텀 객체 다루기(Working with custom objects)
커스텀 객체를 다룰 때는 itemToString과 itemToValue 옵션에 함수를 전달해 항목을 각각 문자열과 값으로 변환하는 방법을 지정할 수 있어요.
기본적으로 항목에서
label과value속성을 찾아요.
import { createListCollection } from '@ark-ui/react/collection'
const collection = createListCollection({
items: [
{ id: 1, name: 'apple' },
{ id: 2, name: 'banana' },
{ id: 3, name: 'cherry' },
],
itemToString: (item) => item.name,
itemToValue: (item) => item.id,
})
항목을 비활성화하려면 isItemDisabled 옵션에 함수를 전달해요.
기본적으로 항목에서
disabled속성을 찾아요.
import { createListCollection } from '@ark-ui/react/collection'
const collection = createListCollection({
items: [
{ id: 1, name: 'apple' },
{ id: 2, name: 'banana' },
{ id: 3, name: 'cherry' },
],
isItemDisabled: (item) => item.id === 2,
})
항목 순서 변경(Reorder items)
reorder 메서드를 사용해 이동할 항목의 시작 인덱스와 끝 인덱스를 전달해 항목 순서를 바꿔요.
const fromIndex = 1 // Banana
const toIndex = 0 // Apple
collection.reorder(fromIndex, toIndex)
console.log(collection.items) // [{ label: "Banana", value: "banana" }, { label: "Apple", value: "apple" }]