日本語

How to Build a Swipe-to-Delete List in React

​​React​CSS,Playwright,Pointer Events,TypeScript

If you keep the amount a row has been dragged to the left in state, and move the row to match the horizontal movement received through Pointer Events, you can build a swipe-to-delete list without a library. If you release after dragging more than 40% of the row's width, the row is deleted. If you release before that, the row returns to its original position.

For touch, the CSS touch-action property is essential. Without it, the browser cancelled the events partway through a horizontal drag, and the row never disappeared. Setting pan-y separates the two: horizontal movement is handled by your own swipe code, and vertical movement is handled by page scrolling.

Note

The test environment was Ubuntu 24.04, Node.js 22.23.4, and Chromium 153. I used React 19.3.1, TypeScript 7.0.2, and Playwright 1.63.0. I operated the mouse and keyboard with Playwright, and sent touch input with the Chrome DevTools Protocol (CDP) Input.dispatchTouchEvent to a screen that imitates a smartphone display. I did not test on a real smartphone, on Firefox or Safari, or with screen reader output. This article also does not cover undoing a deletion or an animation that shrinks the height of the removed row.

In the first attempt, a slight left drag and release returns the row to its place. In the second and third attempts, a large left drag and release removes the row, and the remaining-items count below drops from 5 to 4 and then to 3 and turns pink
Three swipe-left operations with a finger. The circles show the finger position. The circles and the label at the top were overlaid for the GIF.

Keeping the drag distance in state with SwipeRow

I create SwipeRow, a component for one row. Each row has two layers: a pink "Delete" layer underneath and the row contents on top. When the top layer is shifted left with transform: translateX(), the Delete layer underneath comes into view.

tsx
import { useRef, useState } from 'react';
import type { PointerEvent, TransitionEvent } from 'react';

type Props = {
  label: string;
  done: boolean;
  onToggle: () => void;
  onDelete: () => void;
};

// Decide horizontal or vertical once the finger or mouse has moved this far (px)
const SLOP = 10;
// If the row is dragged left past this fraction of its width and released, delete it
const THRESHOLD = 0.4;

type Gesture = {
  pointerId: number;
  startX: number;
  startY: number;
  // 'pending': direction not decided yet / 'swipe': dragging horizontally / 'scroll': vertical, so do nothing
  mode: 'pending' | 'swipe' | 'scroll';
};

export function SwipeRow({ label, done, onToggle, onDelete }: Props) {
  const [offset, setOffset] = useState(0);
  // 'idle': follows the finger / 'back': returning to the original position / 'removing': moving off to the left
  const [phase, setPhase] = useState<'idle' | 'back' | 'removing'>('idle');
  const gesture = useRef<Gesture | null>(null);

  function handlePointerDown(e: PointerEvent<HTMLDivElement>) {
    if (phase === 'removing' || (e.pointerType === 'mouse' && e.button !== 0)) return;
    gesture.current = { pointerId: e.pointerId, startX: e.clientX, startY: e.clientY, mode: 'pending' };
    setPhase('idle');
  }

  function handlePointerMove(e: PointerEvent<HTMLDivElement>) {
    const g = gesture.current;
    if (!g || g.pointerId !== e.pointerId) return;
    const dx = e.clientX - g.startX;
    const dy = e.clientY - g.startY;
    if (g.mode === 'pending') {
      if (Math.abs(dx) < SLOP && Math.abs(dy) < SLOP) return;
      // If horizontal movement is larger, it's a swipe; if vertical, leave it to page scrolling
      g.mode = Math.abs(dx) > Math.abs(dy) ? 'swipe' : 'scroll';
      if (g.mode === 'swipe') {
        // Keep sending events to this element until release, even if the pointer leaves the row
        e.currentTarget.setPointerCapture(e.pointerId);
      }
    }
    if (g.mode === 'swipe') setOffset(Math.min(0, dx)); // Move only to the left
  }

  function handlePointerUp(e: PointerEvent<HTMLDivElement>) {
    const g = gesture.current;
    if (!g || g.pointerId !== e.pointerId) return;
    gesture.current = null;
    if (g.mode !== 'swipe') return;
    const width = e.currentTarget.offsetWidth;
    if (-offset > width * THRESHOLD) {
      // When reduced motion is on, the transition is turned off, so remove the row without waiting for transitionend
      if (window.matchMedia('(prefers-reduced-motion: reduce)').matches) {
        onDelete();
        return;
      }
      setPhase('removing');
      setOffset(-width);
    } else {
      setPhase('back');
      setOffset(0);
    }
  }

  // When the browser starts scrolling or similar and the pointer events are cancelled
  function handlePointerCancel() {
    gesture.current = null;
    setPhase('back');
    setOffset(0);
  }

  function handleTransitionEnd(e: TransitionEvent<HTMLDivElement>) {
    if (phase === 'removing' && e.propertyName === 'transform') onDelete();
  }

  return (
    <li className="row">
      <span className="row-bg" aria-hidden="true">削除</span>
      <div
        className={`row-fg${phase === 'idle' ? '' : ' animate'}`}
        style={{ transform: `translateX(${offset}px)` }}
        onPointerDown={handlePointerDown}
        onPointerMove={handlePointerMove}
        onPointerUp={handlePointerUp}
        onPointerCancel={handlePointerCancel}
        onTransitionEnd={handleTransitionEnd}
      >
        <button
          type="button"
          className="row-label"
          aria-pressed={done}
          onClick={onToggle}
        >
          {label}
        </button>
        <button type="button" className="row-delete" aria-label={`「${label}」を削除`} onClick={onDelete}>
          ×
        </button>
      </div>
    </li>
  );
}

I keep the press position and the horizontal-or-vertical decision in a ref called gesture. Changing a ref's value does not trigger a re-render, so refs suit values that are not shown on screen. Only the values that affect the display are in state: offset, the amount the row is shifted, and phase, which tracks whether the row is returning or being removed.

Right after the press, I do not decide the direction. Once the pointer has moved 10px either horizontally or vertically, I decide: if the horizontal movement is larger, it is a swipe; if the vertical movement is larger, nothing happens. Only when a swipe is decided do I call setPointerCapture(). This way, even if the pointer leaves the row during the drag, the row keeps receiving events until release.

On release, if the drag distance exceeds 40% of the row's width (THRESHOLD), the row moves left to its full width. At the end of that movement, transitionend fires, and I call onDelete so the parent removes the row. If the drag does not reach 40%, offset goes back to 0.

While the finger is dragging, I do not add a transition, so the row follows the finger right away. Only after release do I add the animate class and move the row over 0.2 seconds. The CSS is as follows.

css
.row {
  position: relative;
  overflow: hidden; /* Hide the part of the row that slides out sideways */
  border-bottom: 1px solid #d5dde1;
}

/* Delete background, placed under the row */
.row-bg {
  position: absolute;
  inset: 0;
  display: flex;
  align-items: center;
  justify-content: flex-end;
  padding-right: 20px;
  background: #d85878;
  color: #fff;
  font-weight: bold;
}

.row-fg {
  position: relative;
  display: flex;
  align-items: center;
  background: #fff;
  /* Leave vertical scrolling to the browser and pass only horizontal movement to the page */
  touch-action: pan-y;
  user-select: none;
}
.row-fg.animate { transition: transform 0.2s ease-out; }

@media (prefers-reduced-motion: reduce) {
  .row-fg.animate { transition: none; }
}

touch-action: pan-y is the setting for touch. I explain why in a later section, together with the results of comparing different values.

The App that holds the list

The App that uses SwipeRow keeps the list of rows in state. onDelete removes a row from the list, and pressing the row's label (onToggle) toggles whether it is done.

tsx
import { useState } from 'react';
import { SwipeRow } from './SwipeRow';

type Todo = { id: number; label: string; done: boolean };

const initialTodos: Todo[] = [
  { id: 1, label: '牛乳を買う', done: false },
  { id: 2, label: '本を返す', done: false },
  { id: 3, label: '記事の図を描く', done: false },
  { id: 4, label: '傘を持っていく', done: false },
  { id: 5, label: '植木に水をやる', done: false },
];

export function App() {
  const [todos, setTodos] = useState(initialTodos);

  return (
    <main>
      <ul className="list">
        {todos.map((t) => (
          <SwipeRow
            key={t.id}
            label={t.label}
            done={t.done}
            onToggle={() => setTodos((prev) => prev.map((x) => (x.id === t.id ? { ...x, done: !x.done } : x)))}
            onDelete={() => setTodos((prev) => prev.filter((x) => x.id !== t.id))}
          />
        ))}
      </ul>
      <p className="count">残り {todos.length} 件</p>
    </main>
  );
}

For onDelete and onToggle, I pass a function to setTodos. That way, the function receives the list with all previous updates applied, and it can return a new list.

I also put a "×" button at the right end of each row. Swiping works only with a mouse or touch, so this button is a way to delete for people who use a keyboard. The button has an aria-label such as 「牛乳を買う」を削除 (Delete "Buy milk").

What happens when dragging with the mouse

I set the viewport width to 360px and dragged the first row with Playwright's mouse. The row is 328px wide, so releasing after dragging more than 131.2px to the left deletes it.

text
行の幅: 328px(削除になるのは 131.2px より左へ引いて離したとき)
最初: 牛乳を買う, 本を返す, 記事の図を描く, 傘を持っていく, 植木に水をやる / 残り 5 件
1行目を左へ100px引いて離す: 引いている間 translateX(-100px) / 離した直後 translateX(0px)
  0.4秒後: 牛乳を買う, 本を返す, 記事の図を描く, 傘を持っていく, 植木に水をやる / 残り 5 件 / 1行目 translateX(0px) / イベント: pointerdown pointerup click
1行目を左へ200px引いて離す: 引いている間 translateX(-200px) / 離した直後 translateX(-328px) / 牛乳を買う, 本を返す, 記事の図を描く, 傘を持っていく, 植木に水をやる / 残り 5 件
  0.4秒後: 本を返す, 記事の図を描く, 傘を持っていく, 植木に水をやる / 残り 4 件 / イベント: pointerdown pointerup click
1行目を右へ150px引いて離す: 引いている間 translateX(0px) / 本を返す, 記事の図を描く, 傘を持っていく, 植木に水をやる / 残り 4 件
2行目を下へ150px引いて離す: 引いている間 translateX(0px) / 本を返す, 記事の図を描く, 傘を持っていく, 植木に水をやる / 残り 4 件 / イベント: pointerdown pointerup click
1行目を左へ200px・下へ120px(行の外まで)引いて離す: 引いている間 translateX(-200px)
  0.4秒後: 記事の図を描く, 傘を持っていく, 植木に水をやる / 残り 3 件
2行目をクリック: 記事の図を描く, 傘を持っていく(済), 植木に水をやる / 残り 3 件 / イベント: pointerdown pointerup click
1行目のボタンから Tab で「「記事の図を描く」を削除」へ移って Enter: 傘を持っていく(済), 植木に水をやる / 残り 2 件

When I dragged 100px to the left, the row followed the pointer to translateX(-100px) while dragging and returned to 0 on release. When I dragged 200px, the row moved to -328px (its full width) right after release and was still in the list. 0.4 seconds after release, which is after the 0.2-second movement ends, the row was removed from the list and the count went down to 4.

Dragging to the right does not move the row, because Math.min(0, dx) allows movement only to the left. When I dragged 150px down, the movement was judged vertical, so the row did not move, and the label did not toggle. When I dragged 200px to the left while moving 120px down, past the edge of the row, setPointerCapture() kept the row following the pointer to the end, and the row was deleted.

Clicking the label button marked the item as (済) (done). The "×" button could be focused with Tab and deleted with Enter.

Why the label button's onClick is not called after a drag

The row label is a button, and pressing it toggles whether the item is done. A click also fires after you drag a row and release it, but the label did not toggle. Recording which element received the click gives the following.

text
1行目を左へ100px引いて離す: 牛乳を買う, 本を返す, 記事の図を描く, 傘を持っていく, 植木に水をやる / 残り 5 件 / click の target: row-fg animate
1行目を左へ6px(向きを決める前)だけ動かして離す: 牛乳を買う(済), 本を返す, 記事の図を描く, 傘を持っていく, 植木に水をやる / 残り 5 件 / click の target: row-label

When I dragged 100px to the left, the click was delivered not to the label button (row-label) but to the row contents (row-fg), which had called setPointerCapture(). According to the "click, auxclick, and contextmenu" section of the Pointer Events specification, when pointerup occurs while the pointer is captured, click is sent to the capturing element. Because the label button's onClick is not called, I did not need to add any code to stop the toggle after a drag.

On the other hand, when I moved only 6px and released, the direction had not been decided yet, so no capture happened. The click reached the label button and marked the item as (済) (done). Even if the pointer moves a little after the press, the label button's onClick is still called as long as the movement stays under 10px (SLOP). I checked this with the mouse. I have not tested it with a touch tap.

With reduced motion, transitionend never fires

In the CSS, I remove the transition when the OS "reduce motion" setting (prefers-reduced-motion) is on. In that case, transitionend, which the row removal relies on, never fires. MDN's description of transitionend also says that transition events do not fire when there is no transition duration.

So in SwipeRow, on release I check this setting with window.matchMedia(). If it is on, I call onDelete without waiting for transitionend. Using Playwright's reducedMotion: 'reduce', I compared this with a version that lacks this handling.

text
記事のコード: 1行目を左へ200px引いて離した直後: 本を返す, 記事の図を描く, 傘を持っていく, 植木に水をやる / 残り 4 件 / 1行目 translateX(0px)
  1秒後: 本を返す, 記事の図を描く, 傘を持っていく, 植木に水をやる / 残り 4 件
比べる用(transitionend を待つ版): 1行目を左へ200px引いて離した直後: 牛乳を買う, 本を返す, 記事の図を描く, 傘を持っていく, 植木に水をやる / 残り 5 件 / 1行目 translateX(-328px)
  1秒後: 牛乳を買う, 本を返す, 記事の図を描く, 傘を持っていく, 植木に水をやる / 残り 5 件

In the version without this handling, the row stayed moved to the left (translateX(-328px)), and even after one second it was not removed from the list. In the article's code, the row was removed from the list right after release.

Comparing touch-action values for finger drags

With touch, the browser uses finger movement for scrolling and zooming. According to MDN's description of touch-action, when the browser starts handling a touch gesture itself, the page receives pointercancel. touch-action is a property that sets, per element, which gestures are left to the browser. pan-y leaves only one-finger vertical scrolling to the browser.

I changed touch-action on .row-fg to pan-y, to auto (the same as not specifying it), and to none. Then I sent touch input with CDP to a 360×240 screen. The two operations were dragging the first row 200px to the left with a finger, and moving the finger 140px up over the list.

text
touch-action: pan-y: 1行目を指で左へ200px: 本を返す, 記事の図を描く, 傘を持っていく, 植木に水をやる / 残り 4 件 / イベント: pointerdown pointerup
touch-action: pan-y: 指で上へ140px: scrollY 77(最大 77) / イベント: pointerdown pointercancel
touch-action: auto: 1行目を指で左へ200px: 牛乳を買う, 本を返す, 記事の図を描く, 傘を持っていく, 植木に水をやる / 残り 5 件 / イベント: pointerdown pointercancel
touch-action: auto: 指で上へ140px: scrollY 134(最大 134) / イベント: pointerdown pointercancel
touch-action: none: 1行目を指で左へ200px: 本を返す, 記事の図を描く, 傘を持っていく, 植木に水をやる / 残り 4 件 / イベント: pointerdown pointerup
touch-action: none: 指で上へ140px: scrollY 0(最大 77) / イベント: pointerdown pointerup

With auto, pointercancel arrived partway through the horizontal drag, and the row was not removed. SwipeRow returns the row to its original position when it receives pointercancel, so the swipe was cut off midway. With none, horizontal swipes worked, but moving the finger up did not scroll the page (scrollY stayed at 0). Dragging a finger over the list makes the page impossible to scroll.

With pan-y, dragging horizontally removed the row, and moving the finger vertically scrolled the page. (This comparison sent touch input to Chromium. I have not tested it on a real smartphone.) For vertical movement, pointercancel arrived and the row stayed where it was. The maximum scrollY differs between auto and pan-y because in the pan-y run, a row had already been removed, which made the page shorter.

Point

Set touch-action: pan-y on any element you want to swipe. Your page code handles horizontal movement, and the browser handles vertical scrolling.

​Posted by 86