🔧
React 18以降でドラッグ & ドロップを実装する方法
過去に作ったアプリをメンテナンスしていて、Next.jsのバージョンを最新に上げるとドラッグ & ドロップでリストの並べ替えを実装していた部分が動かなくなっているのに気付いた。
使っているライブラリはこれ。
react-beautiful-dnd
バージョンアップで動かなくなった原因はこれらしい。
動くようにする
日本語でも記事がヒットした。
React 18のStrictModeを使わないようにすればとりあえずは動く。
StrictModeのままでも動くようにするちょっとトリッキーな方法もある。
// 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は今後あまり積極的にはメンテナンスされないようなので、このさい新しいライブラリに置き換えるのもよいかも知れない。
下のやつなんかは良さそうな感じ。
自前で実装する
あるいは、ライブラリに頼らず自前で実装してみるか。
ごくシンプルな要件なら自前実装でも十分かも知れない。
Discussion
dnd-kitちょっと触ってみた程度ですが、インターフェース綺麗でいい感じですね!