DnD Kitは、Reactアプリケーションにドラッグ&ドロップ機能を簡単に組み込むためのモダンなライブラリです。そのシンプルな設計と高いカスタマイズ性により、多くの開発者に利用されています。本記事では、DnD Kitの基本的な使い方と実践的な実装例を紹介します。
[目次を開く]
DnD Kitとは?
DnD Kitは、React環境で使える軽量で柔軟性の高いドラッグ&ドロップライブラリです。以下の特徴を持っています。
- モダンで簡単: HTML5のドラッグ&ドロップAPIを抽象化し、React Hooksベースで実装。
- 高いカスタマイズ性: UIや動作を自由にカスタマイズ可能。
- パフォーマンスに優れる: 仮想DOMに最適化されており、大量の要素を扱う場面でもスムーズ。
- アクセシビリティ対応: キーボード操作やスクリーンリーダーの対応も考慮。
1. DnD Kitのインストール
まずはDnD Kitをインストールします。以下のコマンドを実行してください。
npm install @dnd-kit/core
必要に応じて、以下の追加ライブラリもインストールできます:
-
@dnd-kit/sortable
: 要素の並べ替え機能を提供。 -
@dnd-kit/accessibility
: アクセシビリティを強化。
2. 基本構成
DnD Kitを利用する際の基本的な流れは以下の通りです。
- DndContextで全体をラップする。
- Draggable(ドラッグする要素)とDroppable(ドロップ先の要素)を定義する。
- 必要に応じてカスタマイズやイベントハンドリングを実装。
コード例:シンプルなドラッグ&ドロップ
以下は、DnD Kitを使ったシンプルな実装例です。
import React from 'react';
import { DndContext } from '@dnd-kit/core';
function App() {
const handleDragEnd = (event) => {
const { active, over } = event;
if (over) {
console.log(`Moved ${active.id} to ${over.id}`);
}
};
return (
<DndContext onDragEnd={handleDragEnd}>
<Draggable id="draggable-item">Drag me!</Draggable>
<Droppable id="droppable-area">Drop here!</Droppable>
</DndContext>
);
}
function Draggable({ id, children }) {
return <div id={id} style={{ padding: '8px', backgroundColor: 'lightblue' }}>{children}</div>;
}
function Droppable({ id, children }) {
return <div id={id} style={{ margin: '20px', padding: '8px', backgroundColor: 'lightgray' }}>{children}</div>;
}
export default App;
3. 並べ替え(Sortable)の実装
リスト要素を並べ替えるケースでは、@dnd-kit/sortable
を使います。
インストール
npm install @dnd-kit/sortable
コード例:並べ替え機能の実装
import React, { useState } from 'react';
import { DndContext, closestCenter } from '@dnd-kit/core';
import { arrayMove, SortableContext, useSortable } from '@dnd-kit/sortable';
import { CSS } from '@dnd-kit/utilities';
function SortableList() {
const [items, setItems] = useState(['Item 1', 'Item 2', 'Item 3']);
const handleDragEnd = (event) => {
const { active, over } = event;
if (over && active.id !== over.id) {
const oldIndex = items.indexOf(active.id);
const newIndex = items.indexOf(over.id);
setItems(arrayMove(items, oldIndex, newIndex));
}
};
return (
<DndContext collisionDetection={closestCenter} onDragEnd={handleDragEnd}>
<SortableContext items={items}>
{items.map((item) => (
<SortableItem key={item} id={item} />
))}
</SortableContext>
</DndContext>
);
}
function SortableItem({ id }) {
const { attributes, listeners, setNodeRef, transform, transition } = useSortable({ id });
const style = {
transform: CSS.Transform.toString(transform),
transition,
padding: '8px',
margin: '4px 0',
backgroundColor: 'lightgreen',
border: '1px solid darkgreen',
};
return (
<div ref={setNodeRef} style={style} {...attributes} {...listeners}>
{id}
</div>
);
}
export default SortableList;
※下の画面のItemをドラッグ&ドロップで並び替え出来れば成功です。

4. DnD Kitのアクセシビリティ機能
DnD Kitはデフォルトでアクセシビリティを考慮していますが、さらに@dnd-kit/accessibility
を利用することで、キーボード操作やスクリーンリーダー対応を強化できます。
キーボード操作の有効化
DnD Kitのキーボード操作は、KeyboardSensor
を使用します。
import { DndContext, KeyboardSensor, PointerSensor, useSensor, useSensors } from '@dnd-kit/core';
function App() {
const sensors = useSensors(
useSensor(PointerSensor),
useSensor(KeyboardSensor)
);
return (
<DndContext sensors={sensors}>
{/* ... */}
</DndContext>
);
}
まとめ
DnD Kitを使えば、Reactアプリケーションに柔軟なドラッグ&ドロップ機能を簡単に追加できます。シンプルなDndContextの利用から、SortableContextを使ったリストの並べ替え、さらにアクセシビリティ対応まで、用途に応じた機能を幅広くサポートしているのが魅力です。DnD Kitを活用して、ユーザーフレンドリーなUIを実現してみてください!