List Box Rearrange

PreviousNext

list-box-rearrange-demo

Docs
intentuipage

Preview

Loading preview…
components/docs/collections/list-box/list-box-rearrange-demo.tsx
"use client"

import { useDragAndDrop } from "react-aria-components"
import { useListData } from "react-stately"
import { ListBox, ListBoxItem, ListBoxLabel } from "@/components/ui/list-box"

export default function ListBoxRearrangeDemo() {
  const list = useListData({
    initialItems: [
      { id: "1", name: "Nirvana" },
      { id: "2", name: "Radiohead" },
      { id: "3", name: "Foo Fighters" },
      { id: "4", name: "Arctic Monkeys" },
      { id: "5", name: "The Strokes" },
    ],
  })

  const { dragAndDropHooks } = useDragAndDrop({
    getItems: (keys) =>
      [...keys].map((key) => ({
        "text/plain": list.getItem(key)?.name ?? "",
      })),
    onReorder(e) {
      if (e.target.dropPosition === "before") {
        list.moveBefore(e.target.key, e.keys)
      } else if (e.target.dropPosition === "after") {
        list.moveAfter(e.target.key, e.keys)
      }
    },
  })

  return (
    <ListBox
      className="max-w-2xs"
      items={list.items}
      aria-label="Bands"
      selectionMode="multiple"
      dragAndDropHooks={dragAndDropHooks}
    >
      {(item) => (
        <ListBoxItem key={item.id}>
          <ListBoxLabel>{item.name}</ListBoxLabel>
        </ListBoxItem>
      )}
    </ListBox>
  )
}

Installation

npx shadcn@latest add @intentui/list-box-rearrange-demo

Usage

Usage varies by registry entry. Refer to the registry docs or source files below for details.