use-selection
use-selection
주어진 데이터셋의 선택(selection) 상태를 관리하는 훅이에요. 선택, 선택 해제, 토글, 전체 선택 등을 다루는 핸들러를 제공해요.
출처: 문서
본문
사용법 (Usage)
useSelection 훅에 선택 대상 data 배열을 넘기면 [selection, handlers] 튜플을 반환해요. handlers로 선택 상태를 조작할 수 있어요.
import { Checkbox, Table } from '@mantine/core';
import { useSelection } from '@mantine/hooks';
const elements = [
{ position: 6, mass: 12.011, symbol: 'C', name: 'Carbon' },
{ position: 7, mass: 14.007, symbol: 'N', name: 'Nitrogen' },
{ position: 39, mass: 88.906, symbol: 'Y', name: 'Yttrium' },
{ position: 56, mass: 137.33, symbol: 'Ba', name: 'Barium' },
{ position: 58, mass: 140.12, symbol: 'Ce', name: 'Cerium' },
];
function Demo() {
const positions = useMemo(() => elements.map((element) => element.position), [elements]);
const [selection, handlers] = useSelection({
data: positions,
defaultSelection: [39, 56],
});
const rows = elements.map((element) => {
const isSelected = selection.includes(element.position);
return (
{
if (event.target.checked) {
handlers.select(element.position);
} else {
handlers.deselect(element.position);
}
}}
/>
{element.position}
{element.name}
{element.symbol}
{element.mass}
);
});
return (
{
if (handlers.isAllSelected()) {
handlers.resetSelection();
} else {
handlers.setSelection(elements.map((el) => el.position));
}
}}
/>
Element position
Element name
Symbol
Atomic mass
{rows}
);
}
정의 (Definition)
export interface UseSelectionInput {
/** The array of items to select from */
data: T[];
/** The initial selection, empty array by default */
defaultSelection?: T[];
/** If true, selection is reset when data changes */
resetSelectionOnDataChange?: boolean;
}
export interface UseSelectionHandlers {
/** Add an item to the selection */
select: (selected: T) => void;
/** Remove an item from the selection */
deselect: (deselected: T) => void;
/** Toggle an item's selection state */
toggle: (toggled: T) => void;
/** Returns true if all items from the `data` are selected */
isAllSelected: () => boolean;
/** Returns true if at least one item from the `data` is selected */
isSomeSelected: () => boolean;
/** Set the selection to a specific array of items */
setSelection: (selection: T[]) => void;
/** Clear all selections */
resetSelection: () => void;
}
export type UseSelectionReturnValue = readonly [T[], UseSelectionHandlers];
function useSelection(input: UseSelectionInput): UseSelectionReturnValue
내보내는 타입 (Exported types)
UseSelectionInput, UseSelectionReturnValue, UseSelectionHandlers 타입은 @mantine/hooks 패키지에서 내보내져요. 애플리케이션에서 임포트할 수 있어요.
import type { UseSelectionInput, UseSelectionReturnValue, UseSelectionHandlers } from '@mantine/hooks';