본문으로 바로가기 본문 바로가기
WIKI 기술 지식 베이스

usePickList

원문 보기 위키 갱신

두 목록 사이에서 이동, 재정렬, 그리고 선택적인 드래그 앤 드롭을 관리하는 headless 훅이에요. 소스 목록과 타깃 목록을 오가며 항목을 옮기는 UI는 많지만, 상태를 맞물리게 관리하기가 까다롭죠. usePickList가 그 흐름을 잡아 줘요.

출처: 문서

본문

사용법 (Usage)

import { usePickList } from '@primereact/headless/picklist';
const pickList = usePickList({
    source,
    target,
    selection,
    draggable: true,
    onValueChange: (e) => {
        setSource(e.source);
        setTarget(e.target);
    }
});

<div {...pickList.rootProps}>
    <div {...pickList.sourceListProps}>
        {pickList.state.source.map((item, i) => (
            <div key={i} {...pickList.getOptionProps(item, i, 'source')}>
                {item.name}
            </div>
        ))}
    </div>
    <div>
        <button {...pickList.moveToTargetProps}>→</button>
        <button {...pickList.moveAllToTargetProps}>⇉</button>
        <button {...pickList.moveToSourceProps}>←</button>
        <button {...pickList.moveAllToSourceProps}>⇇</button>
    </div>
    <div {...pickList.targetListProps}>
        {pickList.state.target.map((item, i) => (
            <div key={i} {...pickList.getOptionProps(item, i, 'target')}>
                {item.name}
            </div>
        ))}
    </div>
</div>;

usePickList는 이동과 재정렬 연산을 가진 두 목록을 관리해요. 내장 선택과 키보드 내비게이션이 필요하다면 Listbox와 짝을 지어 쓰세요.

기능 (Features)

  • 두 목록 상태: source와 target 배열을 동기화하고, 어떤 변경에도 단일 onValueChange를 내보내요
  • 이동 연산: 버튼 prop이 미리 연결된 moveToTarget, moveToSource, moveAllToTarget, moveAllToSource
  • 측별 재정렬 컨트롤: 각 목록을 위한 독립적인 prev/next/first/last prop과 짝을 이루는 명령형 메서드
  • 드래그 앤 드롭: 목록 안에서의 포인터 재정렬과 목록 간 이동에 더해 범위 검증을 지원해요
  • 측 인지 옵션 prop: getOptionProps(item, index, 'source' | 'target')가 각 행에 필요한 속성을 돌려줘요

콜백 다루기 (Working with callbacks)

onValueChange, 두 배열을 상태로 유지하기

이동과 재정렬은 모두 onValueChange를 거쳐요. e.source와 e.target을 한 단계로 상태에 다시 적용하면 돼요.

const [source, setSource] = React.useState(initialSource);
const [target, setTarget] = React.useState([]);

const pickList = usePickList({
    source,
    target,
    onValueChange: (e) => {
        setSource(e.source);
        setTarget(e.target);
    }
});

측별 선택 추적하기

선택은 두 목록에 걸쳐 공유돼요. 이동 버튼이 어떤 항목을 옮길지 알 수 있도록 외부에도 그대로 반영해 두세요.

const [selection, setSelection] = React.useState([]);

const pickList = usePickList({
    source,
    target,
    selection,
    onSelectionChange: (e) => setSelection(e.value),
    onValueChange: (e) => {
        setSource(e.source);
        setTarget(e.target);
    }
});

클론 플레이스홀더가 있는 목록 간 드래그

draggable을 켜면 한 번의 동작으로 목록 안 재정렬과 목록 간 이동을 모두 할 수 있어요. 사용자가 원래 위치를 보는 게 유리할 때는 플레이스홀더를 clone으로 바꾸세요.

const pickList = usePickList({
    source,
    target,
    draggable: true,
    placeholder: 'clone',
    onValueChange: (e) => {
        setSource(e.source);
        setTarget(e.target);
    }
});

커스텀 UI에서 이동을 구동하기

키보드 단축키나 메뉴에서 이동을 촉발하고 싶을 때는 명령형 메서드를 직접 호출하면 돼요.

const pickList = usePickList({ source, target, selection, onValueChange });

useHotkey('alt+right', () => pickList.moveToTarget());
useHotkey('alt+shift+right', () => pickList.moveAllToTarget());

데이터 속성으로 스타일링 (Styling with data attributes)

모든 prop 객체에는 CSS 타깃팅을 위한 data-scope과 data-part 속성이 포함돼요.

[data-scope='picklist'][data-part='root'] {
    display: flex;
    gap: 1rem;
}

[data-scope='picklist'][data-part='source-list'],
[data-scope='picklist'][data-part='target-list'] {
    min-height: 200px;
}

[data-sortable-placeholder] {
    opacity: 0.4;
}

옵션 속성 (Option Attributes)

Attribute Value
data-selected Present when the item is selected
data-sortable-item Present on every sortable item
data-sortable-container Container id for the sortable group
data-dragging Present on the item being dragged
data-dropping Present briefly during the drop animation
data-sortable-placeholder Present on the placeholder clone left behind during drag

API

usePickList

접근성 (Accessibility)

방향키로 각 목록 안을 이동하고, Tab으로 목록 사이를 이동하며, Enter로 목록 간 선택을 옮겨요. 전체 WAI-ARIA 준수 세부 사항은 Primitive 문서를 참고하세요.

더 알아보기 (Learn more)