Skip to main content

List

Render caller-defined rows with optional virtual scrolling.

  • Review onboarding designs
    Elena
  • Fix invoice rounding
    Marcus
  • Draft 0.9 release notes
    Priya
Props
Slots

Anatomy#

List [component; slot=root; <ul>]

Usage#

Use List when the caller owns each row’s markup and needs a stable collection surface. Pass items and an itemRender component; List does not take row content through children. Add a virtualizer for large collections only when ordinary rendering becomes costly.

import { List } from 'moraine'

export function Example() {
  return <List items={['Alpha', 'Beta']} itemRender={(item) => <li>{item.item}</li>} />
}

Row ownership#

itemRender receives the item, its index in the full collection, and, with a virtualizer, row props. Spread props onto the outer row element; the virtualizer needs them for positioning and measurement. The root is a <ul> by default and always has role="list", so render list-item semantics in each row, or choose another root with as. TypeScript infers the item and root element types from items and as. emptyRender renders when items is empty or undefined.

<List
  items={rows()}
  emptyRender={<li>No items</li>}
  itemRender={(item) => <li>{item.item.label}</li>}
/>

Virtualization#

createListVirtualizer is an optional adapter from moraine/virtualizer and needs @tanstack/virtual-core. The List root is the scroll container, so give it a bounded height and overflow-y-auto. Row count and scroll behavior follow the estimated or measured row sizes.

import { createListVirtualizer } from 'moraine/virtualizer'

const virtualizer = createListVirtualizer<Item>({
  estimateSize: () => 36,
  getItemKey: (item) => item.id,
})

<List
  as="div"
  items={items}
  virtualizer={virtualizer}
  itemRender={(context) => <div {...context.rowProps}>{context.item.label}</div>}
/>

Read the Virtualization guide for setup, row measurements, stable keys, and keyboard navigation.

Load more at the edges#

onTopReached and onBottomReached fire once each time scrolling reaches the top or bottom edge of an overflowing list; neither fires for the initial position. Combine onBottomReached with scrollThreshold to request the next page shortly before the end.

<List
  class="h-80 overflow-y-auto"
  items={rows()}
  scrollThreshold={48}
  onBottomReached={loadMore}
  itemRender={(context) => <li>{context.item.label}</li>}
/>

Drag to reorder#

createListSortable is an optional adapter from moraine/dnd and needs @dnd-kit/dom. List has no drag props; the sortable composes through itemRender. Wrap the list in sortable.Provider, call sortable.useRow(context) in itemRender, and spread row.props onto the row element. Update the items from onReorder.

import { createListSortable } from 'moraine/dnd'

const sortable = createListSortable({ items, onReorder: (event) => setItems(event.items) })

<sortable.Provider>
  <List
    items={items()}
    itemRender={(context) => {
      const row = sortable.useRow(context)
      return (
        <li {...row.props}>
          <button ref={row.handleRef} aria-label="Reorder">⋮⋮</button>
          {context.item.label}
        </li>
      )
    }}
  />
</sortable.Provider>

row.props keeps the virtual row props from context.rowProps and adds the drag ref, data-dragging, and data-drop-position. With a virtualizer, also pass rangeExtractor: sortable.rangeExtractor to createListVirtualizer so the dragged row stays mounted while it is scrolled out of view. Read the Drag and drop guide for handles, keyboard dragging, and options.

Examples#

Clear an inbox to an empty state#

emptyRender renders when items is empty. List does not invent empty copy; pass the row markup you want shown.

import { Button, List } from 'moraine'
import { createSignal } from 'solid-js'

const INBOX = [
  { id: '1', title: 'Deploy failed on main', from: 'CI' },
  { id: '2', title: 'Review requested on #482', from: 'Elena' },
  { id: '3', title: 'Nightly backup completed', from: 'Ops' },
]

export function EmptyInbox() {
  const [items, setItems] = createSignal(INBOX)

  return (
    <div class="max-w-md w-full space-y-3">
      <List
        items={items()}
        emptyRender={<li class="text-sm text-muted-foreground px-3 py-2">Inbox is empty</li>}
        class="border border-border rounded-md overflow-hidden"
        itemRender={(row) => (
          <li class="px-3 py-2 border-b border-border last:border-b-0">
            <div class="text-sm font-medium">{row.item.title}</div>
            <div class="text-xs text-muted-foreground">{row.item.from}</div>
          </li>
        )}
      />
      <Button
        size="sm"
        variant="outline"
        disabled={items().length === 0}
        onClick={() => setItems([])}
      >
        Clear inbox
      </Button>
    </div>
  )
}

Scroll a large search result set#

Use createListVirtualizer when tens of thousands of rows would otherwise mount at once. Spread context.rowProps onto the measured row element.

import { List } from 'moraine'
import { createListVirtualizer } from 'moraine/virtualizer'

export function Virtualization() {
  const ITEMS = Array.from({ length: 10_000 }, (_, index) => ({
    id: index + 1,
    label: `Result ${index + 1}`,
  }))

  type Item = (typeof ITEMS)[number]

  const virtualizer = createListVirtualizer<Item>({
    estimateSize: () => 36,
    getItemKey: (item) => item.id,
    overscan: 8,
  })

  return (
    <List
      as="div"
      items={ITEMS}
      virtualizer={virtualizer}
      role="list"
      aria-label="Virtual results"
      class="border border-border rounded-md h-72 w-full overflow-y-auto"
      itemRender={(context) => (
        <div {...context.rowProps} role="listitem">
          <div class="px-3 border-b border-border flex h-9 items-center">{context.item.label}</div>
        </div>
      )}
    />
  )
}

Reorder a checklist from a grip handle#

The grip button is the drag handle, so it also starts a keyboard drag with Space or Enter. Arrow keys move to the next row, and Space, Enter, or Escape ends the drag.

import { Icon, List } from 'moraine'
import { createListSortable } from 'moraine/dnd'
import { createSignal } from 'solid-js'

const TASKS = [
  { id: 'design', label: 'Review the release notes draft' },
  { id: 'qa', label: 'Run the regression suite' },
  { id: 'docs', label: 'Publish the migration guide' },
  { id: 'notify', label: 'Announce the release' },
  { id: 'retro', label: 'Schedule the retrospective' },
]

export function Sortable() {
  const [tasks, setTasks] = createSignal(TASKS)
  const sortable = createListSortable({
    items: tasks,
    onReorder: (event) => setTasks(event.items),
  })

  return (
    <sortable.Provider>
      <List
        items={tasks()}
        aria-label="Release checklist"
        class="border border-border rounded-md max-w-md w-full overflow-hidden"
        itemRender={(context) => {
          const row = sortable.useRow(context)
          return (
            <li
              {...row.props}
              class="text-sm px-2 py-2 border-b border-border bg-background flex gap-2 items-center last:border-b-0 data-[dnd-dragging]:opacity-60 data-[drop-position=after]:shadow-[inset_0_-2px_0_var(--primary)] data-[drop-position=before]:shadow-[inset_0_2px_0_var(--primary)]"
            >
              <button
                ref={row.handleRef}
                type="button"
                aria-label={`Reorder ${context.item.label}`}
                class="text-muted-foreground rounded-sm flex size-6 cursor-grab items-center justify-center hover:bg-accent"
              >
                <Icon name="i-lucide:grip-vertical" />
              </button>
              {context.item.label}
            </li>
          )
        }}
      />
    </sortable.Provider>
  )
}

Reorder a long virtual playlist#

Drag a row toward the list edge to scroll. The row is its own handle here.

import { List } from 'moraine'
import { createListSortable } from 'moraine/dnd'
import { createListVirtualizer } from 'moraine/virtualizer'
import { createSignal } from 'solid-js'

export function SortableVirtualization() {
  const [items, setItems] = createSignal(
    Array.from({ length: 5_000 }, (_, index) => ({ id: index + 1, label: `Track ${index + 1}` })),
  )

  type Item = ReturnType<typeof items>[number]

  const sortable = createListSortable({
    items,
    onReorder: (event) => setItems(event.items),
  })
  const virtualizer = createListVirtualizer<Item>({
    estimateSize: () => 36,
    getItemKey: (item) => item.id,
    overscan: 8,
    // Keeps the dragged row mounted while it is scrolled out of view.
    rangeExtractor: sortable.rangeExtractor,
  })

  return (
    <sortable.Provider>
      <List
        as="div"
        items={items()}
        virtualizer={virtualizer}
        role="list"
        aria-label="Playlist"
        class="border border-border rounded-md h-72 w-full overflow-y-auto"
        itemRender={(context) => {
          const row = sortable.useRow(context)
          return (
            <div
              {...row.props}
              role="listitem"
              class="bg-background cursor-grab data-[dnd-dragging]:opacity-60 data-[drop-position=after]:shadow-[inset_0_-2px_0_var(--primary)] data-[drop-position=before]:shadow-[inset_0_2px_0_var(--primary)]"
            >
              <div class="text-sm px-3 border-b border-border flex h-9 items-center">
                {context.item.label}
              </div>
            </div>
          )
        }}
      />
    </sortable.Provider>
  )
}

Render result rows with extra detail lines#

Estimate a larger size when row height varies, and let the virtualizer measure after mount.

import { List } from 'moraine'
import { createListVirtualizer } from 'moraine/virtualizer'
import { For } from 'solid-js'

export function DynamicHeight() {
  const ITEMS = Array.from({ length: 1_000 }, (_, index) => ({
    id: index + 1,
    label: `Result ${index + 1}`,
    details: Array.from(
      { length: (index % 4) + 1 },
      (_, detailIndex) => `Detail line ${detailIndex + 1} for result ${index + 1}.`,
    ),
  }))

  type Item = (typeof ITEMS)[number]

  const virtualizer = createListVirtualizer<Item>({
    estimateSize: () => 96,
    getItemKey: (item) => item.id,
    gap: 8,
    overscan: 8,
  })

  return (
    <List
      as="div"
      items={ITEMS}
      virtualizer={virtualizer}
      role="list"
      aria-label="Variable-height results"
      class="py-2 border border-border rounded-md h-80 w-full overflow-y-auto"
      itemRender={(context) => (
        <div {...context.rowProps} role="listitem">
          <div class="mx-2 px-3 py-2 border border-border rounded-md">
            <div class="font-medium">{context.item.label}</div>
            <div class="text-sm text-muted-foreground">
              <For each={context.item.details}>
                {(detail) => <span class="block">{detail}</span>}
              </For>
            </div>
          </div>
        </div>
      )}
    />
  )
}

API Reference#

Props#

Renders a <ul> element by default.

Prop