🔧

React 18以降でドラッグ & ドロップを実装する方法

2023/01/13に公開1

過去に作ったアプリをメンテナンスしていて、Next.jsのバージョンを最新に上げるとドラッグ & ドロップでリストの並べ替えを実装していた部分が動かなくなっているのに気付いた。

使っているライブラリはこれ。
react-beautiful-dnd

バージョンアップで動かなくなった原因はこれらしい。

https://github.com/atlassian/react-beautiful-dnd/issues/2399

動くようにする

日本語でも記事がヒットした。
https://zenn.dev/takuty/articles/2e375cb349bfc4

React 18のStrictModeを使わないようにすればとりあえずは動く。

StrictModeのままでも動くようにするちょっとトリッキーな方法もある。
https://medium.com/@wbern/getting-react-18s-strict-mode-to-work-with-react-beautiful-dnd-47bc909348e4

// StrictModeDroppable.tsx
// Credits to https://github.com/GiovanniACamacho and https://github.com/Meligy for the TypeScript version
// Original post: https://github.com/atlassian/react-beautiful-dnd/issues/2399#issuecomment-1175638194
import { useEffect, useState } from "react";
import { Droppable, DroppableProps } from "react-beautiful-dnd";
export const StrictModeDroppable = ({ children, ...props }: DroppableProps) => {
  const [enabled, setEnabled] = useState(false);
  useEffect(() => {
    const animation = requestAnimationFrame(() => setEnabled(true));
    return () => {
      cancelAnimationFrame(animation);
      setEnabled(false);
    };
  }, []);
  if (!enabled) {
    return null;
  }
  return <Droppable {...props}>{children}</Droppable>;
};

別のライブラリに変更する

react-beautiful-dndは今後あまり積極的にはメンテナンスされないようなので、このさい新しいライブラリに置き換えるのもよいかも知れない。

下のやつなんかは良さそうな感じ。

https://zenn.dev/aldagram_tech/articles/c2cf248bd016fc

https://dndkit.com/

自前で実装する

あるいは、ライブラリに頼らずに自前で実装してみるか。

https://reffect.co.jp/react/react-table-re-order

ごくシンプルな要件なら自前実装でも十分かも知れない。

https://developer.mozilla.org/ja/docs/Web/API/HTML_Drag_and_Drop_API

Discussion

きうきうきうきう

dnd-kitちょっと触ってみた程度ですが、インターフェース綺麗でいい感じですね!