1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【Next.js × DnD-kit】スマホDnD最適化+localStorage永続化まとめ

1
Posted at

職場で使えるかなと開発に挑戦している「看護師向け計算ツールアプリ」。
並べ替え機能を作ったけど、Next.js + DnD-kit でスマホDnDを作ると、デフォルトでは以下の問題が出やすいとのこと。

  • タップ直後にドラッグ扱い
  • 指ブレで誤発火
  • 並び替えが保存されない
  • flex/gridで座標が狂う

本記事はUX最適化(delay/tolerance)+ 保存機能(localStorage) をまとめて実装する。

■ PointerSensor 設定(誤操作防止)

const sensors = useSensors(
  useSensor(PointerSensor, {
    activationConstraint: {
      delay: 150,
      tolerance: 5,
    },
  })
);

✔ 効果

  • タップ=クリック
  • 長押し=DnD
  • 指ブレの誤発火を抑制

■ 並び順を localStorage に保存

lib/sortOrder.ts

export const saveOrder = (order: string[]) => {
  if (typeof window === "undefined") return;
  localStorage.setItem("calcOrder", JSON.stringify(order));
};

export const loadOrder = () => {
  if (typeof window === "undefined") return [];
  return JSON.parse(localStorage.getItem("calcOrder") ?? "[]");
};

初回ロード:

useEffect(() => {
  const saved = loadOrder();
  setOrder(saved.length ? saved : DEFAULT_ORDER);
}, []);

DnD終了時:

const newOrder = arrayMove(order, oldIndex, newIndex);
setOrder(newOrder);
saveOrder(newOrder);

■ レイアウトは columns+verticalListSortingStrategy

<SortableContext items={order} strategy={verticalListSortingStrategy}>
  <ul className="columns-1 sm:columns-2 md:columns-3 space-y-3">
    {items.map((item) => (
      <SortableButton key={item.id} id={item.id} />
    ))}
  </ul>
</SortableContext>

✔ スマホ1〜2列、PC3列でも安定動作。

■ トースト通知(UX向上)

triggerToast("✅ 並び順を保存しました");

■ まとめ

  • delay / tolerance でスマホDnDが安定
  • localStorage で端末永続化
  • columns+verticalList が最も動作が安定
  • Next.js の SSR では window ガード必須

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?