Drag-to-Reorder Table Columns in React with dnd-kit
To reorder table columns by dragging, keep the column order as an array of ids in state, and attach dnd-kit's useSortable to the body cells as well as the header cells. This way the whole column moves while you drag it, and the array order changes when you drop it. This approach is useful for moving frequently viewed columns to the left in admin list tables and inventory tables.
In a test environment, I made a 4-column by 4-row table and swapped columns with the mouse and the keyboard. With the keyboard, the dnd-kit function as provided got stuck at columns of different widths. I also describe how I fixed that.
The test environment was Ubuntu 24.04 and Node.js 22.23.4. I used react / react-dom 19.3.1, @dnd-kit/core 6.3.1, @dnd-kit/sortable 10.0.0, @dnd-kit/utilities 3.2.2, @dnd-kit/modifiers 9.0.0, @types/react 19.3.0, typescript 7.0.2, and esbuild 0.28.2. I type-checked the .tsx files with tsc, built them for production with esbuild, and ran them in Chromium 153 (headless, operated with Playwright 1.63.0). I did not wrap the app in StrictMode.
I did not test touch operation on smartphones and other devices, wide tables that scroll horizontally, saving the column order, or reading the table with a screen reader.

- 1. Column definitions and the column order state
- 2. The full table component
- 3. Also apply useSortable to body cells so the whole column moves
- 4. Use CSS.Translate for transform
- 5. Use restrictToHorizontalAxis to keep columns from moving up or down
- 6. Move columns one at a time with the keyboard when widths differ
Column definitions and the column order state
The table shows a list of products. Each column has an id, a header label, and a function that returns the cell content.
import type { ReactNode } from 'react';
export type Product = { id: number; name: string; category: string; price: number; stock: number };
export const rows: Product[] = [
{ id: 1, name: 'ノート A5 方眼', category: '文具', price: 220, stock: 48 },
{ id: 2, name: 'ステンレスマグ', category: '日用品', price: 1980, stock: 12 },
{ id: 3, name: 'USB-C ケーブル 1m', category: '電子機器', price: 880, stock: 0 },
{ id: 4, name: '付箋 75mm', category: '文具', price: 330, stock: 105 },
];
export type ColumnId = 'name' | 'category' | 'price' | 'stock';
export type Column = { id: ColumnId; label: string; cell: (row: Product) => ReactNode };
export const columns: Column[] = [
{ id: 'name', label: '商品名', cell: (r) => r.name },
{ id: 'category', label: '分類', cell: (r) => r.category },
{ id: 'price', label: '価格', cell: (r) => `${r.price.toLocaleString('ja-JP')}円` },
{ id: 'stock', label: '在庫', cell: (r) => r.stock },
];
Inside the component, the only thing kept in state is the array of column ids in order (columnOrder). When rendering, the column definitions are looked up in this array's order to build the header row and each body row. Reordering columns means changing the order of this array.
The full table component
Install the following four packages. @dnd-kit/modifiers is used to restrict the drag movement to the horizontal axis only.
npm install @dnd-kit/core @dnd-kit/sortable @dnd-kit/utilities @dnd-kit/modifiers
Here is the full table component. columnKeyboardCoordinates is a custom function for keyboard movement, and I show its code in a later section. The last <p> is there so I can check the column order as text.
import { useState, type CSSProperties } from 'react';
import {
DndContext,
KeyboardSensor,
PointerSensor,
closestCenter,
useSensor,
useSensors,
type DragEndEvent,
} from '@dnd-kit/core';
import { restrictToHorizontalAxis } from '@dnd-kit/modifiers';
import {
SortableContext,
arrayMove,
horizontalListSortingStrategy,
useSortable,
} from '@dnd-kit/sortable';
import { CSS } from '@dnd-kit/utilities';
import { columnKeyboardCoordinates } from './columnKeyboardCoordinates';
import { columns, rows, type Column, type ColumnId, type Product } from './columns';
const columnById = new Map(columns.map((c) => [c.id, c]));
// Give the header cell and the body cells of the same column the same movement, using the same column id
function useColumnCell(id: ColumnId) {
const sortable = useSortable({ id });
const style: CSSProperties = {
transform: CSS.Translate.toString(sortable.transform),
transition: sortable.transition,
position: 'relative',
zIndex: sortable.isDragging ? 1 : 0,
background: sortable.isDragging ? '#eefafd' : undefined,
};
return { ...sortable, style };
}
function HeaderCell({ column }: { column: Column }) {
const { setNodeRef, setActivatorNodeRef, attributes, listeners, style } = useColumnCell(column.id);
return (
<th ref={setNodeRef} style={style} data-col={column.id}>
<button
type="button"
ref={setActivatorNodeRef}
className="handle"
aria-label={`${column.label}の列を動かす`}
{...attributes}
{...listeners}
>
⠿
</button>
{column.label}
</th>
);
}
function BodyCell({ column, row }: { column: Column; row: Product }) {
const { setNodeRef, style } = useColumnCell(column.id);
return (
<td ref={setNodeRef} style={style} data-col={column.id}>
{column.cell(row)}
</td>
);
}
export function ReorderableTable() {
const [columnOrder, setColumnOrder] = useState<ColumnId[]>(() => columns.map((c) => c.id));
const sensors = useSensors(
useSensor(PointerSensor),
useSensor(KeyboardSensor, { coordinateGetter: columnKeyboardCoordinates }),
);
function handleDragEnd({ active, over }: DragEndEvent) {
if (!over || active.id === over.id) return;
setColumnOrder((order) =>
arrayMove(order, order.indexOf(active.id as ColumnId), order.indexOf(over.id as ColumnId)),
);
}
const ordered = columnOrder.map((id) => columnById.get(id)!);
return (
<DndContext
sensors={sensors}
collisionDetection={closestCenter}
modifiers={[restrictToHorizontalAxis]}
onDragEnd={handleDragEnd}
>
<SortableContext items={columnOrder} strategy={horizontalListSortingStrategy}>
<table>
<thead>
<tr>
{ordered.map((column) => (
<HeaderCell key={column.id} column={column} />
))}
</tr>
</thead>
<tbody>
{rows.map((row) => (
<tr key={row.id}>
{ordered.map((column) => (
<BodyCell key={column.id} column={column} row={row} />
))}
</tr>
))}
</tbody>
</table>
</SortableContext>
<p id="order">{columnOrder.join(',')}</p>
</DndContext>
);
}
I pass the column order array to items of SortableContext, and specify horizontalListSortingStrategy as the layout strategy. In handleDragEnd, which runs on drop, I find the position of the dragged column (active.id) and the position of the column it was over at that moment (over.id). Then arrayMove moves the dragged column to the position of the column it was over. The columns in between each shift by one.
I placed DndContext outside <table>. The TanStack Table official example of reordering columns with dnd-kit (column-dnd example) also has a comment saying that DndContext renders a div element, so it should not be placed inside <table>.
I made the drag start only from the "⠿" button placed to the left of the header label. The listeners and attributes returned by useSortable are attached to this button, not to the <th>. In the test environment, I pressed the part of the product name header away from the handle (the right side, outside the button) and dragged it 213px to the right. The column did not move, and the order did not change. I also pass this button to setActivatorNodeRef. The @dnd-kit/core distributed code looks up this element as the place to return focus to after a drag that started with the keyboard ends.
In the test environment (Chromium 153), I dragged the handle of the product name column 213px to the right, to the center of the price column, and dropped it. The column order changed from name,category,price,stock to category,price,name,stock. I reloaded the page to return to the initial order. Then I moved the stock column to the leftmost position, where the product name was, and the order became stock,name,category,price. Next, I moved the price column to the position of category, and the order became stock,name,price,category.
Also apply useSortable to body cells so the whole column moves
If useSortable is attached only to the header <th>, only the header moves while you drag. The body <td> cells stay in place, and they are redrawn in the new order only when you drop.

In the version where the body cells are plain <td> elements without useSortable, the dragged product name header got a transform that shifts it 213px to the right (matrix(1, 0, 0, 1, 213, 0)). However, the transform of the product name <td> cells in rows 1 and 4 stayed none.
In the finished version, BodyCell also calls useSortable with the same column id as the header. Using the same id is the same approach as DragAlongCell, which renders the body cells in the TanStack Table example mentioned above. As a result, the product name <td> cells in rows 1 and 4 also received the same matrix(1, 0, 0, 1, 213, 0) as the header, and the whole column moved together. The category and price columns, which were pushed aside, also moved 166px to the left, with the header and the cells in row 1 moving together.
To use the same code for headers and body cells, I put the transform and other settings into one hook, useColumnCell. Every cell gets position: relative. Only the column being dragged gets zIndex: 1, so it is displayed in front of the other columns. The TanStack Table example uses the same settings.
Use CSS.Translate for transform
When passing the transform returned by useSortable to style, use CSS.Translate.toString. dnd-kit also has CSS.Transform.toString, but according to the distributed code, it creates a string that combines the movement with a scale (CSS.Scale). CSS.Translate.toString only produces translate3d(x, y, 0).
When I did the same drag with CSS.Transform.toString, the product name column being dragged got matrix(0.487534, 0, 0, 1, 213, 0), and its width shrank to about half. This value is roughly the width of the overlapped price column (81px) divided by the width of the product name column (166px), which is about 0.488. The @dnd-kit/core distributed code runs the transform of the dragged element through a process (adjustScale) that adjusts it to the size of the element it overlaps. In a table where the column widths are not uniform, the width of the dragged column changes to match the column it overlaps, so I use CSS.Translate. The TanStack Table example also uses CSS.Translate.toString, with a comment saying to use translate instead of transform so the column does not get squashed.
Use restrictToHorizontalAxis to keep columns from moving up or down
restrictToHorizontalAxis, passed to modifiers of DndContext, is the function described in the @dnd-kit/modifiers README as "restricts movement to the horizontal axis." In the distributed code, it is a function that just sets the y of the transform to 0 and returns it.
I dragged the mouse 213px to the right while also moving it 80px down. In the version without restrictToHorizontalAxis, the transform of the dragged product name column became matrix(1, 0, 0, 1, 213, 80), and the whole column shifted 80px downward. In the finished version with the modifier, the value stayed matrix(1, 0, 0, 1, 213, 0), and the column did not move up or down. The column order after dropping was category,price,name,stock in both versions.
Move columns one at a time with the keyboard when widths differ
With dnd-kit's KeyboardSensor, focusing a handle and pressing the Space key starts the drag. You move with the arrow keys and confirm with the Space key again. The Esc key cancels. Which position an arrow key moves to is decided by the function passed as coordinateGetter to KeyboardSensor. @dnd-kit/sortable provides sortableKeyboardCoordinates for sortable lists. I used it in another article on this blog, about reordering a vertical list with dnd-kit.
However, when I used sortableKeyboardCoordinates in this table, the product name column got stuck partway. I focused the product name handle with the Tab key, pressed Space, and then pressed the Right arrow key four times. On the first press, it swapped with the category column. On the second press, it moved slightly to the right but did not swap with the price column. From the third press on, it did not move at all. The order confirmed with Space was category,name,price,stock.
The column widths in the test environment were 166px for product name, 89px for category, 81px for price, and 75px for stock. Looking at the distributed code of sortableKeyboardCoordinates, when moving to the next column, it calculates a position that aligns the right edge of the dragged column with the right edge of the destination column. When the wide product name column is aligned with the right edge of the narrow price column, the center of the product name column does not reach the center of the price column. It stays about midway between the centers of the category and price columns, about 42px away from each. The closestCenter used for collision detection is described in its type definition comments as returning the item whose center is closest. I think this explains why it did not swap with the price column on the second press and could not move further. As a test, I made the column widths almost equal (167 to 170px) with CSS. With that table, sortableKeyboardCoordinates worked as is: each Right arrow press moved one column, and the order confirmed was category,price,stock,name.
So I wrote a function that moves to the center of the adjacent column with the Right and Left arrow keys. coordinateGetter is called each time a key is pressed during a drag, and it returns the new position of the dragged element.
import type { KeyboardCoordinateGetter } from '@dnd-kit/core';
// Move to the center of the adjacent column with the left/right arrow keys (moves one column at a time even when the widths differ)
export const columnKeyboardCoordinates: KeyboardCoordinateGetter = (event, { context }) => {
if (event.code !== 'ArrowLeft' && event.code !== 'ArrowRight') return undefined;
event.preventDefault();
const { over, collisionRect, droppableRects } = context;
if (!over || !collisionRect) return undefined;
// Sort the column positions recorded when the drag started, from left to right
const ids = [...droppableRects.keys()].sort(
(a, b) => droppableRects.get(a)!.left - droppableRects.get(b)!.left,
);
const next = ids[ids.indexOf(over.id) + (event.code === 'ArrowRight' ? 1 : -1)];
if (next === undefined) return undefined;
const rect = droppableRects.get(next)!;
return {
x: rect.left + rect.width / 2 - collisionRect.width / 2,
y: collisionRect.top,
};
};
The function finds the column next to the current column (over) from droppableRects, which holds the position of each column. It then returns a position where the center of the dragged column overlaps the center of that column. The returned value is the top-left coordinate of the dragged element. The @dnd-kit/core KeyboardSensor code builds the current position from left and top of collisionRect, so this function returns values in the same form. For keys other than the left and right arrow keys, it returns undefined and does nothing.
With this function in place, the product name column moved one column at a time to the category, price, and stock positions each time I pressed the Right arrow key. On the fourth press, it was already at the right end, so it did not move. The order confirmed with Space was category,price,stock,name. After confirming, focus stayed on the product name handle button. When I pressed the Right arrow key twice and then the Esc key, the order stayed name,category,price,stock.
When moving columns of different widths with the keyboard, pass a coordinateGetter that moves to the center of the adjacent column, instead of sortableKeyboardCoordinates.





