Skip to content

Instantly share code, notes, and snippets.

@paulwoods
Last active August 19, 2019 19:36
Show Gist options
  • Save paulwoods/3e5374a6fa318d52d9bdbd9c92b90005 to your computer and use it in GitHub Desktop.
Save paulwoods/3e5374a6fa318d52d9bdbd9c92b90005 to your computer and use it in GitHub Desktop.
React DND sorts table trows in a tbody (react 16.9.0, react-beautiful-dnd 11.0.5)
import React from 'react';
import ReactDOM from 'react-dom';
import { DragDropContext, Droppable, Draggable } from 'react-beautiful-dnd';
///////////////////////////////////////////////////////////////////////
class Tbody extends React.Component {
render() {
const { provided, innerRef, children } = this.props;
return <tbody {...provided.droppableProps} ref={innerRef}>
{children}
</tbody>
}
}
///////////////////////////////////////////////////////////////////////
class Row extends React.Component {
render() {
const {provided, innerRef} = this.props;
return <tr
{...provided.draggableProps}
{...provided.dragHandleProps}
ref={innerRef}
>
<td>{this.props.row[0]}</td>
<td>{this.props.row[1]}</td>
<td>{this.props.row[2]}</td>
</tr>
}
}
///////////////////////////////////////////////////////////////////////
class App extends React.Component {
state = { rows:
[
["a", "alpha", "aaaaa"],
["b", "bravo", "bbbbb"],
["c", "charlie", "ccccc"],
["d", "delta", "ddddd"],
]
}
onDragEnd = result => {
console.log('onDragEnd', result);
}
render() {
return <div>
<h1>Hello World</h1>
<DragDropContext onDragEnd={this.onDragEnd}>
<Droppable droppableId="droppable">
{ provided => (
<table>
<thead>
<tr>
<th>action</th>
<th>name</th>
<th>field</th>
</tr>
</thead>
<Tbody provided={provided} innerRef={provided.innerRef}>
{this.state.rows.map((row, index) => <Draggable draggableId={row[0]} key={index} index={index}>
{ provided => (
<Row provided={provided} innerRef={provided.innerRef} row={row}/>
)}
</Draggable>)}
{provided.placeholder}
</Tbody>
</table>
)}
</Droppable>
</DragDropContext>
</div>
}
}
ReactDOM.render(<App />, document.getElementById('root'));
@paulwoods
Copy link
Author

This example show how to implement drag-and-drop for the rows in the body of an HTML table.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment