Skip to content
Browse documentation

A list row that slides over its actions: cells grow with your finger, a full swipe runs the first one, and the row folds away.

Used forEmail and inbox listsTask and to-do listsNotification and message listsOrder and ticket queues

Install with the shadcn CLI

$ npx shadcn@latest add @hairline/swipe-actions

Older shadcn CLI, or a network that blocks ui.shadcn.com? Install by URL: shadcn add https://hairlineui.com/r/swipe-actions.json. More

Templates

Need the whole page?

65 Next.js landing pages, each designed from scratch. Try any of them live; one is $39, all of them $159, and 8 are free.

Where it’s used

  • Email and inbox lists

    Swipe to archive, delete or mark as read.

  • Task and to-do lists

    Complete or snooze a task with a swipe.

  • Notification and message lists

    Quick actions on each row.

  • Order and ticket queues

    Handle many items quickly on a phone.

What it handles for you

Most web lists copy swipe actions badly: a row that slides to show two buttons and nothing more. This works the way mail apps do, and has buttons for people who don’t swipe.

Instead of wiring upswipe gesture codeaction cellsa full-swipe shortcutoptimistic removal with rollbackhover action buttons
  1. Actions that grow with your finger

    The cells under the edge share the space the row uncovers, and each icon scales in once there is room.

  2. A full swipe runs the first action

    Keep going past most of the row and the first action arms, taking the whole space. Letting go runs it.

  3. Trackpads work too

    A two-finger swipe on a trackpad drives the row in the same way.

  4. Removal that can fail

    A removing action slides the row off and folds it away. If it fails, the row comes back, shakes and reads Failed.

  5. Buttons for a mouse

    With a fine pointer, hovering or focusing the row shows the same actions as icon buttons. This is the accessible path.

  6. One row open at a time

    Opening one row closes the other, and a tap on an open row closes it.

Overview

Most web lists copy swipe actions badly: a row that slides to show two buttons and nothing more. This one works the way mail apps do. Drag a row, or swipe two fingers on a trackpad, and the actions under that edge share the space it uncovers: every cell grows with the finger and its icon scales in once there is room. Let go past half the rail and the row springs open; keep going past most of the row and the first action arms, taking the whole space with its icon riding the row's edge, and letting go runs it. Actions that remove the row slide it off and fold its height away at once, and if the work fails the row unfolds, slides back and shakes. With a mouse the row's time gives way to the same actions as icons on hover, so nothing depends on the gesture.

States

reveal
After 7px of mostly horizontal movement the row follows the pointer on one transform; vertical movement is left to the page. The cells under that edge share the uncovered space equally, and each icon scales from 0.72 and fades in as its cell passes about 50px.
open
Released past half the rail (76px per action), or flicked outward faster than 0.45px/ms, the row springs open; otherwise it springs closed. Tapping the row, pointing anywhere else, Escape or opening another row closes it.
arm
Past 62% of the row the first action takes over the whole space in about 60ms and its icon rides the row's edge, with a 6ms vibration on phones. Coming back 24px disarms it. Releasing while armed runs it.
remove
An action with removes slides the row off (critically damped) and folds its height in 380ms before onAction settles. If onAction throws, the row unfolds, springs back, shakes and its time reads Failed for 2.6s.
hover
On devices with a fine pointer, hovering or focusing the row fades the time out and the actions in as 28px icon buttons over a soft edge of the row's own colour.

Usage

usage.tsx
import { SwipeActions } from "@/components/swipe-actions";import { Archive, MailOpen } from "lucide-react";<SwipeActions  label={message.subject}  meta={message.time}  leading={[{ id: "read", label: "Read", icon: <MailOpen />, tone: "primary", onAction: markRead }]}  trailing={[{ id: "archive", label: "Archive", icon: <Archive />, tone: "primary", removes: true, onAction: archive }]}>  <MessagePreview message={message} /></SwipeActions>

An inbox where delete can fail

Removal is optimistic: the row leaves as soon as the swipe commits. Throw from onAction to bring it back; take the item out of your list once it resolves.

example.tsx
"use client";import { SwipeActions } from "@/components/swipe-actions";import { Mail, MailOpen, Trash2 } from "lucide-react";export function Inbox({ messages, setMessages }) {  return (    <div className="overflow-hidden rounded-2xl border [&>*:last-child]:-mb-px">      {messages.map((m) => (        <SwipeActions          key={m.id}          label={m.subject}          meta={m.time}          leading={[{            id: "read", label: m.unread ? "Read" : "Unread", icon: m.unread ? <MailOpen /> : <Mail />, tone: "primary",            onAction: () => fetch("/api/messages/" + m.id, { method: "PATCH", body: JSON.stringify({ unread: !m.unread }) }),          }]}          trailing={[{            id: "delete", label: "Delete", icon: <Trash2 />, tone: "destructive", removes: true,            onAction: async () => {              const res = await fetch("/api/messages/" + m.id, { method: "DELETE" });              if (!res.ok) throw new Error("Could not delete");              setMessages((list) => list.filter((x) => x.id !== m.id));            },          }]}        >          <p className="truncate text-sm font-medium">{m.from}</p>          <p className="truncate text-xs text-muted-foreground">{m.subject}</p>        </SwipeActions>      ))}    </div>  );}

Props

label
string
Names the row for screen readers and in announcements, e.g. the subject.
leading
SwipeAction[]
Under the left edge, revealed by swiping right. The first runs on a full swipe.
trailing
SwipeAction[]
Under the right edge, listed from the edge inward. The first runs on a full swipe.
SwipeAction
{ id, label, icon, tone?, removes?, onAction }
tone is "neutral" (muted), "primary" or "destructive". removes slides the row off and folds it away; onAction may return a promise and throw to undo that.
meta
ReactNode
At the row's end, e.g. the time. Gives way to the action icons on hover.
enter= false
boolean
Unfold on mount, for a row put back by an undo.
divider= true
boolean
A hairline under the row that folds away with it. Clip the last one with -mb-px on the list.
disabled= false
boolean
No gestures and no actions.

Accessibility and motion

  • The icon buttons are the accessible actions: they are real buttons in the tab order, shown on hover or focus, with the action as their name. The swipe cells repeat them for pointers and are hidden from assistive technology.
  • Results are announced in a status region: done, or failed with an invitation to try again. Escape closes an open row.
  • Only one row is open at a time, as in mail apps. A tap on an open row closes it instead of following whatever is under it, and a click that ends a drag is swallowed.
  • Drags and trackpad swipes write transforms only, and one frame loop runs the spring and the arming, then sleeps. Each cell is a full-height layer moved by transform, so revealing never changes layout.
  • Reduced motion turns springs, folds and the shake into immediate changes; the colours, labels and announcements still say what happened.

Requirements

React 19, Tailwind CSS v4 and shadcn/ui theme variables (any style, light and dark). Icons from lucide-react.

Source

'use client';/* ───────────────────────────────────────────────────────── * SWIPE ACTIONS: a list row that slides over its actions * *   reveal    drag the row (or swipe two fingers on a *             trackpad) and the actions under that edge share *             the space it uncovers: each cell grows with the *             finger and its icon scales in once there's room *   open      let go past half the rail, or flick, and the row *             springs open with the actions at full size; tap *             the row, anywhere else or Escape to close it. *             Opening one row closes the others *   arm       keep going past most of the row and the first *             action takes the whole space, its icon riding the *             row's edge (a tick on phones). Let go to run it *   remove    an action that removes the row (archive, delete) *             slides it off and folds its height away at once; *             if the work fails, the row unfolds, slides back, *             shakes, and its time reads "Failed" *   hover     with a mouse, the row's time gives way to the same *             actions as icons, so nothing needs a swipe * * The icon buttons are the accessible actions: Tab reaches them, * and results are announced. The swipe cells repeat them for * pointers and stay out of the tab order. * ───────────────────────────────────────────────────────── */import * as React from 'react';import { EASE_OUT, INTERACTION_FOCUS, useInteractionReducedMotion } from './ui-interaction-motion';import { type SwipeSide, useSwipeRow } from './use-swipe-row';export type SwipeTone = 'neutral' | 'primary' | 'destructive';export interface SwipeAction {  id: string;  label: string;  icon: React.ReactNode;  tone?: SwipeTone;  /** The row leaves the list (archive, delete): it slides out and folds away at once, and comes back if onAction throws. Remove the item from your list when it resolves. */  removes?: boolean;  onAction: () => void | Promise<void>;}export interface SwipeActionsProps extends Omit<React.HTMLAttributes<HTMLDivElement>, 'children'> {  /** Names the row for screen readers, e.g. the message subject. */  label: string;  /** Under the left edge, revealed by swiping right. The first one runs on a full swipe. */  leading?: SwipeAction[];  /** Under the right edge, revealed by swiping left, listed from the edge inward. The first one runs on a full swipe. */  trailing?: SwipeAction[];  /** At the row's end, e.g. the time. With a mouse it gives way to the actions on hover. */  meta?: React.ReactNode;  /** Unfold on mount, for a row put back by an undo. */  enter?: boolean;  /** A hairline under the row, folding away with it. */  divider?: boolean;  disabled?: boolean;  children: React.ReactNode;}const CELL = 76;const NONE: SwipeAction[] = [];const TONES: Record<SwipeTone, string> = {  neutral: 'bg-muted text-foreground shadow-[inset_1px_0_0_var(--border),inset_-1px_0_0_var(--border)]',  primary: 'bg-primary text-primary-foreground',  destructive: 'bg-destructive text-white',};// Cells start off the row; after that the engine owns their transforms, so these objects never change.const OFF: Record<SwipeSide, React.CSSProperties> = { leading: { transform: 'translate3d(-100%,0,0)', visibility: 'hidden' }, trailing: { transform: 'translate3d(100%,0,0)', visibility: 'hidden' } };const HIDDEN: React.CSSProperties = { opacity: 0 };export function SwipeActions({ label, leading = NONE, trailing = NONE, meta, enter = false, divider = true, disabled = false, children, className = '', ...props }: SwipeActionsProps) {  const reduced = useInteractionReducedMotion();  const [gone, setGone] = React.useState(enter && !reduced);  const [failed, setFailed] = React.useState(false);  const [said, setSaid] = React.useState('');  const busy = React.useRef(false);  const alive = React.useRef(true);  const body = React.useRef<HTMLDivElement>(null);  const timers = React.useRef(new Set<ReturnType<typeof setTimeout>>());  const lists = React.useRef({ leading, trailing });  React.useLayoutEffect(() => {    lists.current = { leading, trailing };  });  const wait = (ms: number) => new Promise<void>((resolve) => {    const t = setTimeout(() => { timers.current.delete(t); resolve(); }, reduced ? 0 : ms);    timers.current.add(t);  });  const run = async (side: SwipeSide, index: number, via: 'swipe' | 'cell' | 'button') => {    const action = lists.current[side][index];    if (!action || busy.current || disabled) return;    busy.current = true;    setFailed(false);    try {      if (action.removes) {        // Optimistic: the row leaves now, and comes back only if the work fails.        await row.commit(side, index);        if (!alive.current) return;        setGone(true);        try {          await action.onAction();          if (alive.current) setSaid(`${label}: ${action.label} done`);        } catch {          if (!alive.current) return;          setGone(false);          await wait(360);          row.restore();          await wait(420);          fail(action);        }        return;      }      if (via === 'swipe') await row.commit(side, index);      else row.close();      let ok = true;      try { await action.onAction(); } catch { ok = false; }      if (!alive.current) return;      if (via === 'swipe') { await wait(140); row.restore(); }      if (ok) setSaid(`${label}: ${action.label} done`);      else { await wait(380); fail(action); }    } finally {      busy.current = false;    }  };  const fail = (action: SwipeAction) => {    if (!alive.current) return;    setFailed(true);    setSaid(`${label}: ${action.label} failed. Try again.`);    if (!reduced) body.current?.animate([{ transform: 'none' }, { transform: 'translateX(-5px)' }, { transform: 'translateX(5px)' }, { transform: 'translateX(-3px)' }, { transform: 'none' }], { duration: 380, easing: 'ease-out' });    const t = setTimeout(() => { timers.current.delete(t); setFailed(false); }, 2600);    timers.current.add(t);  };  const row = useSwipeRow({ leading: leading.length, trailing: trailing.length, cellWidth: CELL, reduced, disabled, onFull: (side) => void run(side, 0, 'swipe') });  React.useEffect(() => {    alive.current = true;    const pending = timers.current;    return () => { alive.current = false; pending.forEach(clearTimeout); };  }, []);  // A row put back by an undo unfolds once it's mounted.  React.useEffect(() => {    if (!gone || !enter) return;    let b = 0;    const a = requestAnimationFrame(() => { b = requestAnimationFrame(() => setGone(false)); });    return () => { cancelAnimationFrame(a); cancelAnimationFrame(b); };    // eslint-disable-next-line react-hooks/exhaustive-deps  }, []);  // Labels changed (Read ↔ Unread): measure the faces again.  const labels = [...leading, ...trailing].map((a) => a.label).join('|');  React.useEffect(() => { row.remeasure(); }, [labels]); // eslint-disable-line react-hooks/exhaustive-deps  const cellsFor = (side: SwipeSide, list: SwipeAction[]) =>    list.map((action, i) => (      <button        key={`${side}-${action.id}`}        ref={(el) => row.attachCell(side, i, el)}        type="button"        tabIndex={-1}        aria-hidden="true"        onClick={() => void run(side, i, 'cell')}        className={`absolute inset-y-0 left-0 w-full cursor-pointer will-change-transform ${TONES[action.tone ?? 'neutral']}`}        style={OFF[side]}      >        <span ref={(el) => row.attachFace(side, i, el)} className="absolute left-0 top-1/2 flex -translate-y-1/2 flex-col items-center gap-1 whitespace-nowrap text-[11px] font-medium will-change-transform [&_svg]:size-[18px] [&_svg]:stroke-[1.75]" style={HIDDEN}>          {action.icon}          {action.label}        </span>      </button>    ));  // Mouse users get the same actions as icons: the row's own edge first, so the order matches the swipe.  const buttons = [...leading.map((a, i) => ({ a, side: 'leading' as const, i })), ...[...trailing].reverse().map((a) => ({ a, side: 'trailing' as const, i: trailing.indexOf(a) }))];  return (    <div      className={`grid ${className}`}      style={{ gridTemplateRows: gone ? '0fr' : '1fr', opacity: gone ? 0 : 1, transition: reduced ? 'none' : `grid-template-rows 380ms ${EASE_OUT} ${gone ? '120ms' : '0ms'}, opacity ${gone ? 260 : 320}ms ${EASE_OUT} ${gone ? '160ms' : '0ms'}` }}      {...props}    >      <div className="min-h-0 overflow-hidden">        <div          ref={(el) => row.attachSurface(el)}          role="group"          aria-label={label}          data-failed={failed || undefined}          onKeyDown={(e) => { if (e.key === 'Escape' && row.open) { e.preventDefault(); row.close(); } }}          className={`group/row relative isolate touch-pan-y overflow-hidden ${divider ? 'border-b border-border' : ''}`}        >          {cellsFor('leading', leading)}          {cellsFor('trailing', trailing)}          <div            ref={(el) => row.attachFront(el)}            className={`relative z-30 flex items-center gap-3 bg-(--row-bg) px-4 py-3 transition-[background-color] duration-200 will-change-transform [--row-bg:var(--background)] pointer-fine:group-hover/row:[--row-bg:color-mix(in_oklab,var(--muted)_55%,var(--background))] ${disabled ? 'opacity-60' : 'cursor-grab active:cursor-grabbing'}`}          >            <div ref={body} className="min-w-0 flex-1">{children}</div>            <div className="relative flex shrink-0 items-center self-stretch">              <span className="grid text-right text-[11.5px] tabular-nums text-muted-foreground transition-opacity duration-200 pointer-fine:group-hover/row:opacity-0 group-focus-within/row:opacity-0 group-data-[moving]/row:opacity-100! group-data-[failed]/row:opacity-100!">                <span className="col-start-1 row-start-1 transition-[opacity,filter] duration-300" style={{ opacity: failed ? 0 : 1, filter: failed ? 'blur(3px)' : 'none' }}>{meta}</span>                <span className="col-start-1 row-start-1 text-red-600 transition-[opacity,filter] duration-300 dark:text-red-400" style={{ opacity: failed ? 1 : 0, filter: failed ? 'none' : 'blur(3px)' }}>Failed</span>              </span>              {buttons.length > 0 && (                <div className="pointer-events-none absolute right-0 top-1/2 flex -translate-y-1/2 translate-x-1 items-center gap-0.5 pl-6 opacity-0 transition-[opacity,transform] duration-200 pointer-fine:group-hover/row:pointer-events-auto pointer-fine:group-hover/row:translate-x-0 pointer-fine:group-hover/row:opacity-100 group-focus-within/row:pointer-events-auto group-focus-within/row:translate-x-0 group-focus-within/row:opacity-100 group-data-[moving]/row:pointer-events-none! group-data-[moving]/row:opacity-0! group-data-[failed]/row:pointer-events-none! group-data-[failed]/row:opacity-0!"                  style={{ background: 'linear-gradient(to right, transparent, var(--row-bg) 18px)' }}>                  {buttons.map(({ a, side, i }) => (                    <button                      key={`${side}-${a.id}`}                      type="button"                      aria-label={a.label}                      title={a.label}                      disabled={disabled}                      onClick={() => void run(side, i, 'button')}                      className={`flex size-7 cursor-pointer items-center justify-center rounded-full text-muted-foreground transition-[background-color,color,box-shadow] duration-150 hover:bg-background hover:shadow-[0_0_0_1px_var(--border)] disabled:cursor-default [&_svg]:size-4 [&_svg]:stroke-[1.75] ${a.tone === 'destructive' ? 'hover:text-red-600 dark:hover:text-red-400' : 'hover:text-foreground'} ${INTERACTION_FOCUS}`}                    >                      {a.icon}                    </button>                  ))}                </div>              )}            </div>          </div>        </div>      </div>      <span role="status" className="sr-only">{said}</span>    </div>  );}

Registry item: /r/swipe-actions.json