Skip to content

Early previewhamur is not on npm yet. The components are being built in the open, follow along on GitHub.

InputsReact

Sortable List

A list the user puts in order.

Rendered by React 19.3.1

Loading React…
import { SortableList } from '@hamur/react/sortable-list'

const tasks = [
  'Plan the sprint',
  'Review pull requests',
  'Fix the flaky test',
  'Write the release notes',
  'Update the changelog',
]

function GripIcon() {
  return (
    <svg
      className="sortable-list-icon"
      width="16"
      height="16"
      viewBox="0 0 24 24"
      aria-hidden="true"
    >
      <path d="M9 5h.01M15 5h.01M9 12h.01M15 12h.01M9 19h.01M15 19h.01" />
    </svg>
  )
}

export default function SortableListExample() {
  return (
    <div className="stack">
      <h3 id="sortable-list-today" className="sortable-list-heading">
        Today
      </h3>
      <SortableList.Root className="sortable-list" defaultValue={tasks}>
        <SortableList.List
          className="sortable-list-list"
          aria-labelledby="sortable-list-today"
        >
          {(item: string) => (
            <SortableList.Item
              key={item}
              className="sortable-list-item"
              value={item}
            >
              <SortableList.Handle className="sortable-list-handle">
                <GripIcon />
              </SortableList.Handle>
              <span className="sortable-list-text">{item}</span>
            </SortableList.Item>
          )}
        </SortableList.List>
      </SortableList.Root>
    </div>
  )
}
Not measured yetTests passing in React
18.2 KiBSize
Not measured yetMemory
Not measured yetSpeed
[N] commits

Installation

npm i @hamur/react

Not on npm yet. The package goes out under the chosen name.

Anatomy

Import the component and assemble its parts:

<SortableList.Root>
  <SortableList.List>
    <SortableList.Item>
      <SortableList.Handle />
    </SortableList.Item>
  </SortableList.List>
</SortableList.Root>

// Not in this example: SortableList.MoveButton

Examples

Item Drag

A playlist with dragActivator="item": the whole row drags with the mouse, a touch after a hold; the Handle stays for keys.

SortableListItemDrag.tsx
import { SortableList } from '@hamur/react/sortable-list'

const tracks = ['Morning light', 'Slow river', 'Paper planes', 'Night shift']

function GripIcon() {
  return (
    <svg
      className="sortable-list-icon"
      width="16"
      height="16"
      viewBox="0 0 24 24"
      aria-hidden="true"
    >
      <path d="M9 5h.01M15 5h.01M9 12h.01M15 12h.01M9 19h.01M15 19h.01" />
    </svg>
  )
}

export default function SortableListItemDragExample() {
  return (
    <div className="stack">
      <SortableList.Root className="sortable-list" defaultValue={tracks} dragActivator="item">
        <SortableList.List className="sortable-list-list" aria-label="Playlist">
          {(item: string) => (
            <SortableList.Item
              key={item}
              className="sortable-list-item sortable-list-draggable"
              value={item}
            >
              <SortableList.Handle className="sortable-list-handle">
                <GripIcon />
              </SortableList.Handle>
              <span className="sortable-list-text">{item}</span>
            </SortableList.Item>
          )}
        </SortableList.List>
      </SortableList.Root>
    </div>
  )
}

Horizontal

Four stages in a row with orientation="horizontal", moved with the left and right arrows.

SortableListHorizontal.tsx
import { SortableList } from '@hamur/react/sortable-list'

const stages = ['Draft', 'Review', 'Approve', 'Publish']

function GripIcon() {
  return (
    <svg
      className="sortable-list-icon"
      width="16"
      height="16"
      viewBox="0 0 24 24"
      aria-hidden="true"
    >
      <path d="M9 5h.01M15 5h.01M9 12h.01M15 12h.01M9 19h.01M15 19h.01" />
    </svg>
  )
}

export default function SortableListHorizontalExample() {
  return (
    <div className="stack">
      <SortableList.Root className="sortable-list" defaultValue={stages} orientation="horizontal">
        <SortableList.List className="sortable-list-list" aria-label="Stages">
          {(item: string) => (
            <SortableList.Item key={item} className="sortable-list-item" value={item}>
              <SortableList.Handle className="sortable-list-handle">
                <GripIcon />
              </SortableList.Handle>
              <span className="sortable-list-text">{item}</span>
            </SortableList.Item>
          )}
        </SortableList.List>
      </SortableList.Root>
    </div>
  )
}

Grid

Six shortcuts in a three column grid, a place with the left and right arrows and a row with the up and down.

SortableListGrid.tsx
import { SortableList } from '@hamur/react/sortable-list'

const shortcuts = ['Photos', 'Music', 'Maps', 'Notes', 'Mail', 'Clock']

function GripIcon() {
  return (
    <svg
      className="sortable-list-icon"
      width="16"
      height="16"
      viewBox="0 0 24 24"
      aria-hidden="true"
    >
      <path d="M9 5h.01M15 5h.01M9 12h.01M15 12h.01M9 19h.01M15 19h.01" />
    </svg>
  )
}

export default function SortableListGridExample() {
  return (
    <div className="stack">
      <SortableList.Root className="sortable-list" defaultValue={shortcuts} orientation="grid">
        <SortableList.List className="sortable-list-list" aria-label="Shortcuts">
          {(item: string) => (
            <SortableList.Item key={item} className="sortable-list-item" value={item}>
              <SortableList.Handle className="sortable-list-handle">
                <GripIcon />
              </SortableList.Handle>
              <span className="sortable-list-text">{item}</span>
            </SortableList.Item>
          )}
        </SortableList.List>
      </SortableList.Root>
    </div>
  )
}

Move Buttons

Drinks with MoveButtons and no Handle: nothing drags, each button moves its item and is announced.

SortableListMoveButtons.tsx
import { SortableList } from '@hamur/react/sortable-list'

const drinks = ['Espresso', 'Americano', 'Flat white', 'Cortado']

function UpIcon() {
  return (
    <svg
      className="sortable-list-icon"
      width="16"
      height="16"
      viewBox="0 0 24 24"
      aria-hidden="true"
    >
      <path d="M6 15l6-6 6 6" />
    </svg>
  )
}

function DownIcon() {
  return (
    <svg
      className="sortable-list-icon"
      width="16"
      height="16"
      viewBox="0 0 24 24"
      aria-hidden="true"
    >
      <path d="M6 9l6 6 6-6" />
    </svg>
  )
}

export default function SortableListMoveButtonsExample() {
  return (
    <div className="stack">
      <SortableList.Root className="sortable-list" defaultValue={drinks}>
        <SortableList.List className="sortable-list-list" aria-label="Drinks">
          {(item: string) => (
            <SortableList.Item key={item} className="sortable-list-item" value={item}>
              <span className="sortable-list-text">{item}</span>
              <SortableList.MoveButton className="sortable-list-move" to="previous">
                <UpIcon />
              </SortableList.MoveButton>
              <SortableList.MoveButton className="sortable-list-move" to="next">
                <DownIcon />
              </SortableList.MoveButton>
            </SortableList.Item>
          )}
        </SortableList.List>
      </SortableList.Root>
    </div>
  )
}

Locked

Sections with canMove: the cover and the appendix stay where they are and the others skip their places.

SortableListLocked.tsx
import { SortableList } from '@hamur/react/sortable-list'

const sections = ['Cover', 'Introduction', 'Method', 'Results', 'Appendix']
const locked = new Set(['Cover', 'Appendix'])
const canMove = ({ to, value }: { to: number; value: readonly string[] }) => !locked.has(value[to])

function GripIcon() {
  return (
    <svg
      className="sortable-list-icon"
      width="16"
      height="16"
      viewBox="0 0 24 24"
      aria-hidden="true"
    >
      <path d="M9 5h.01M15 5h.01M9 12h.01M15 12h.01M9 19h.01M15 19h.01" />
    </svg>
  )
}

export default function SortableListLockedExample() {
  return (
    <div className="stack">
      <SortableList.Root className="sortable-list" defaultValue={sections} canMove={canMove}>
        <SortableList.List className="sortable-list-list" aria-label="Sections">
          {(item: string) => (
            <SortableList.Item
              key={item}
              className="sortable-list-item"
              value={item}
              disabled={locked.has(item)}
            >
              <SortableList.Handle className="sortable-list-handle">
                <GripIcon />
              </SortableList.Handle>
              <span className="sortable-list-text">{item}</span>
              {locked.has(item) ? <span className="sortable-list-fixed">fixed</span> : null}
            </SortableList.Item>
          )}
        </SortableList.List>
      </SortableList.Root>
    </div>
  )
}

Controlled

The order held by the app, with Handles and MoveButtons, a Reset from outside and the last move from the event details.

SortableListControlled.tsx
import * as React from 'react'
import { SortableList } from '@hamur/react/sortable-list'

const initial = ['Ship it', 'Write tests', 'Review docs', 'Tag the release']

function GripIcon() {
  return (
    <svg
      className="sortable-list-icon"
      width="16"
      height="16"
      viewBox="0 0 24 24"
      aria-hidden="true"
    >
      <path d="M9 5h.01M15 5h.01M9 12h.01M15 12h.01M9 19h.01M15 19h.01" />
    </svg>
  )
}

function UpIcon() {
  return (
    <svg
      className="sortable-list-icon"
      width="16"
      height="16"
      viewBox="0 0 24 24"
      aria-hidden="true"
    >
      <path d="M6 15l6-6 6 6" />
    </svg>
  )
}

function DownIcon() {
  return (
    <svg
      className="sortable-list-icon"
      width="16"
      height="16"
      viewBox="0 0 24 24"
      aria-hidden="true"
    >
      <path d="M6 9l6 6 6-6" />
    </svg>
  )
}

export default function SortableListControlledExample() {
  const [value, setValue] = React.useState(initial)
  const [change, setChange] = React.useState('none yet')
  return (
    <div className="stack">
      <SortableList.Root
        className="sortable-list"
        value={value}
        onValueChange={(next: string[], details: SortableList.Root.ChangeEventDetails<string>) => {
          setValue(next)
          setChange(
            `${details.item} from ${details.from + 1} to ${details.to + 1} by ${details.reason}`,
          )
        }}
      >
        <SortableList.List className="sortable-list-list" aria-label="Release steps">
          {(item: string) => (
            <SortableList.Item key={item} className="sortable-list-item" value={item}>
              <SortableList.Handle className="sortable-list-handle">
                <GripIcon />
              </SortableList.Handle>
              <span className="sortable-list-text">{item}</span>
              <SortableList.MoveButton className="sortable-list-move" to="previous">
                <UpIcon />
              </SortableList.MoveButton>
              <SortableList.MoveButton className="sortable-list-move" to="next">
                <DownIcon />
              </SortableList.MoveButton>
            </SortableList.Item>
          )}
        </SortableList.List>
      </SortableList.Root>
      <div className="row">
        <button
          type="button"
          className="button sortable-list-reset"
          onClick={() => {
            setValue(initial)
            setChange('reset by the app')
          }}
        >
          Reset
        </button>
      </div>
      <p className="muted sortable-list-value">Order: {value.join(', ')}</p>
      <p className="muted sortable-list-change">Last change: {change}</p>
    </div>
  )
}

Form

A ranking in a Field and Form, submitted as priorities in the shown order and brought back by a reset.

SortableListForm.tsx
import * as React from 'react'
import { Field } from '@hamur/react/field'
import { Form } from '@hamur/react/form'
import { SortableList } from '@hamur/react/sortable-list'

const criteria = ['Speed', 'Price', 'Quality', 'Support']

function GripIcon() {
  return (
    <svg
      className="sortable-list-icon"
      width="16"
      height="16"
      viewBox="0 0 24 24"
      aria-hidden="true"
    >
      <path d="M9 5h.01M15 5h.01M9 12h.01M15 12h.01M9 19h.01M15 19h.01" />
    </svg>
  )
}

export default function SortableListFormExample() {
  const [submitted, setSubmitted] = React.useState('')
  return (
    <Form
      className="stack"
      onFormSubmit={(_values, details) => {
        const form = details.event.target as HTMLFormElement
        setSubmitted([...new FormData(form)].map(([key, value]) => `${key}=${value}`).join('&'))
      }}
    >
      <Field.Root name="priorities" className="field">
        <Field.Label className="sortable-list-heading" nativeLabel={false} render={<div />}>
          Rank what matters most
        </Field.Label>
        <SortableList.Root className="sortable-list" defaultValue={criteria}>
          <SortableList.List className="sortable-list-list">
            {(item: string) => (
              <SortableList.Item key={item} className="sortable-list-item" value={item}>
                <SortableList.Handle className="sortable-list-handle">
                  <GripIcon />
                </SortableList.Handle>
                <span className="sortable-list-text">{item}</span>
              </SortableList.Item>
            )}
          </SortableList.List>
        </SortableList.Root>
      </Field.Root>
      <div className="row">
        <button className="button" type="submit">
          Save
        </button>
        <button className="button" type="reset" onClick={() => setSubmitted('')}>
          Reset
        </button>
      </div>
      {submitted ? <pre className="output">{submitted}</pre> : null}
    </Form>
  )
}

API reference

24 props across 5 parts, in React syntax. className, style, render are listed once, under Shared props.

HandleSortableList.Handle

The button that picks its Item up: Space or Enter, a click, or a pointer drag. Renders a <button>.

Handle props
PropTypeDefault
nativeButtonWhether the component renders a native <button> element when replacing itbooleantrue
focusableWhenDisabledWhether the Handle stays focusable while it cannot move its Item.booleantrue
Handle data attributes
Data attributeDescription
data-grabbedPresent when the item is held by a key press or a click on the handle.
data-draggingPresent when the item is the one being moved, by pointer or keyboard.
data-disabledPresent when the item or the sortable list is disabled.

ItemSortableList.Item

One entry of the list, for one item of the value. Renders a <li>.

Item props
PropTypeDefault
valuerequiredThe item this entry shows: an entry of the Root's value.any—
disabledWhether the item cannot be moved.booleanfalse
Item data attributes
Data attributeDescription
data-indexThe item's index in the committed value.
data-disabledPresent when the item or the sortable list is disabled.
data-draggingPresent when the item is the one being moved, by pointer or keyboard.
data-grabbedPresent when the item is held by a key press or a click on its handle.

ListSortableList.List

The list of items, in the value's order. Renders an <ol>.

List props
PropTypeDefault
childrenThe Items, or a function that renders one for each item of the value, in order.React.ReactNode | ((item: any, index: number) => React.ReactNode)—
List data attributes
Data attributeDescription
data-orientationThe layout the items are ordered in.
data-disabledPresent when the sortable list is disabled.
data-emptyPresent when the list has no items.
data-sortingPresent while an item is grabbed or dragged past the drag threshold.

MoveButtonSortableList.MoveButton

A button that moves its Item one place, or to the start or the end. While the move does not apply it is aria-disabled and keeps focus. Renders a <button>.

MoveButton props
PropTypeDefault
nativeButtonWhether the component renders a native <button> element when replacing itbooleantrue
torequiredWhere the button moves its Item: one place back or forward, or to the start or the end.SortableListMoveTarget—
focusableWhenDisabledWhether the button stays focusable while its move does not apply.booleantrue
MoveButton data attributes
Data attributeDescription
data-toWhere the button moves the item.
data-disabledPresent when the move does not apply: the item is at that end, the item or the sortable list is disabled, or canMove refuses every target in that direction.

RootSortableList.Root

Groups a sortable list and owns its value: every item, in order. Renders a <div>.

Root props
PropTypeDefault
valueEvery item, in order.readonly Item[]—
defaultValueEvery item, in order, when the component is initially rendered, and what a form resetreadonly Item[][]
onValueChangeEvent handler called once per committed move.((value: Item[], eventDetails: SortableListRoot.ChangeEventDetails<Item>) => void)—
isItemEqualToValueCustom comparison logic used to tell two items apart.((item: Item, other: Item) => boolean)—
itemToStringLabelConverts an item to the text its Handle and MoveButtons are named and announced with.((item: Item) => string)—
itemToStringValueConverts an item to the string submitted with a form.((item: Item) => string)—
canMoveWhether an item may be moved to a place.((details: SortableListCanMoveDetails<Item>) => boolean)—
orientationThe layout the keys and the drag follow: a column, a row, or a wrapping grid.SortableListOrientation'vertical'
dragActivatorWhat a pointer drag starts from: the Handle only, or anywhere on an Item but its controls.SortableListDragActivator'handle'
longPressDelayHow long, in milliseconds, a touch on an Item's body is held before it drags.number250
disabledWhether the component should ignore user interaction.booleanfalse
readOnlyWhether the user should be unable to move items.booleanfalse
nameIdentifies the field when a form is submitted: one entry per item, in order.string—
formIdentifies the form that owns the hidden inputs.string—
labelsThe texts of the names, the instructions and the announcements.Partial<SortableListLabels>—
actionsRefA ref to imperative actions.React.Ref<SortableListRoot.Actions<Item>>—
Root data attributes
Data attributeDescription
data-orientationThe layout the items are ordered in.
data-disabledPresent when the sortable list is disabled.
data-readonlyPresent when the sortable list does not allow changing the order.
data-emptyPresent when the list has no items.
data-sortingPresent while an item is grabbed or dragged past the drag threshold.
data-validPresent when the sortable list is in a valid state (when wrapped in Field.Root).
data-invalidPresent when the sortable list is in an invalid state (when wrapped in Field.Root).
data-touchedPresent when the sortable list has been touched (when wrapped in Field.Root).
data-dirtyPresent when the sortable list's order has changed (when wrapped in Field.Root).
data-filledPresent when the list has items (when wrapped in Field.Root).
data-focusedPresent when an element inside the sortable list is focused (when wrapped in Field.Root).

Shared props

Every part that renders an element takes these.

Shared props
PropType
classNameCSS class applied to the element, or a function that returns a class based on the component's state.string | ((state: State) => string | undefined)
styleStyle applied to the element, or a function that returns a style object based on the component's state.React.CSSProperties | ((state: State) => React.CSSProperties | undefined)
renderAllows you to replace the component's HTML element with a different tag, or compose it with another component.React.ReactElement<unknown, string | React.JSXElementConstructor<any>> | ComponentRenderFn<HTMLProps, State>

Keyboard and accessibility

Keyboard

Keyboard
KeysDoesPart
SpaceEnterPicks the item up; again, drops it where it isHandle
ArrowUpArrowDownWhile picked up, moves the item one place (a row in a grid); ArrowLeft and ArrowRight in a row, swapped in a right-to-left pageHandle
HomeEndWhile picked up, moves the item to the first or last place that is allowedHandle
AltArrowUpAltArrowDownWith nothing picked up, moves the item one place earlier or later at once; focus staysHandle
EscapeWhile picked up, puts the item back and says so; a surrounding Dialog stays openHandle

Accessibility

What the parts set
PartSetsSo that
Roota role="status" region, polite and atomic, and a hidden description of the keyseach pick up, step, drop, cancel and move is said once
Listrole="list", named by the Field label, aria-labelledby or aria-labelthe list is said with its name and its count
Itemrole="listitem", no tabindex; data-index is its placethe list reports its items and their count, and the page has one tab stop per Handle
Handlea button named "Reorder {name}", aria-pressed while picked up, aria-describedby the instructions, aria-keyshortcuts="Alt+ArrowUp Alt+ArrowDown"the button says what it moves, whether it holds it and which keys move it
Handlearia-disabled, not disabled, when the item cannot movea locked item's handle keeps focus and the reader says why nothing happens
MoveButtona button named "Move {name} up", "down", "left", "right", "to start" or "to end"; aria-disabled where the move does not applythe button path says where the item goes, and focus stays on it after a press

Focus order

  1. Every Handle and MoveButton is a tab stop, in DOM order; there is no roving focus and an Item takes none.
  2. Picking up, stepping and dropping keep focus on the Handle. After a move the Handle of the moved item has focus in its new place.
  3. Tab, or a click outside the List, cancels a pick up. Nothing takes focus on mount or on a form reset.