While learning how to use react-beautiful-dnd
library, I've found that (when I'm building the library required structure) if I define components outside the main app, it works on React but it does not work on Gatsby (development), it starts to work but then errors appear
But if I move those components inside the main app, then it also works on Gatsby
The example code:
export default () => {
const [elements, setElements] = useState(myElements)
const onDragEnd = result => {
const { destination, source} = result
if (!destination) return
if (destination.droppableId === source.droppableId && destination.index === source.index) return
const new_elements = reorder(elements, source.droppableId, destination.droppableId, source.index, destination.index)
setElements(new_elements)
}
const Columns = ({ arr }) =>
arr.map((col, i) => (
<Droppable droppableId={col.columnId} key={i}>
{(provided, snapshot) => (
<Ul ref={provided.innerRef}>
<Elements arr={col.items} />
{provided.placeholder}
</Ul>
)}
</Droppable>
))
const Elements = ({ arr }) =>
arr.map((el, j) => (
<Draggable draggableId={el.id} index={j} key={j}>
{(provided, snapshot) => (
<Li ref={provided.innerRef} {...provided.draggableProps} {...provided.dragHandleProps}>
{el.text}
</Li>
)}
</Draggable>
))
return (
<DragDropContext onDragEnd={onDragEnd}>
<Grid>
<Columns arr={myElements} />
</Grid>
</DragDropContext>
)
}
So if Columns
and Elements
are defined outside, it's not working (but it is with React)
Why is this happening?
(the sandbox: https://codesandbox.io/s/using-react-beautiful-dnd-with-hooks-bfwzl?fontsize=14&hidenavigation=1&theme=dark)
As said in the docs https://github.com/atlassian/react-beautiful-dnd/blob/master/docs/api/draggable.md#keys-for-a-list-of-draggable-
Your key should not include the index of the item
Once changed this, it works as expected
<Droppable droppableId={col.columnId} key={col.columnId}>
<Draggable draggableId={el.id} index={j} key={el.id}>