Skip to content

Instantly share code, notes, and snippets.

@nemrosim
Created October 7, 2020 19:35
Show Gist options
  • Save nemrosim/f2f16e8b4582b106623ae6902e7d0097 to your computer and use it in GitHub Desktop.
Save nemrosim/f2f16e8b4582b106623ae6902e7d0097 to your computer and use it in GitHub Desktop.
import React, { useState } from 'react';
import './App.css';
import { DndProvider, useDrag, useDrop } from "react-dnd";
import { HTML5Backend } from "react-dnd-html5-backend";
const MovableItem = ({setIsFirstColumn}) => {
const [{isDragging}, drag] = useDrag({
item: {name: 'Any custom name', type: 'Our first type'},
end: (item, monitor) => {
const dropResult = monitor.getDropResult();
if(dropResult && dropResult.name === 'Column 1'){
setIsFirstColumn(true)
} else {
setIsFirstColumn(false);
}
},
collect: (monitor) => ({
isDragging: monitor.isDragging(),
}),
});
const opacity = isDragging ? 0.4 : 1;
return (
<div ref={drag} className='movable-item' style={{opacity}}>
We will move this item
</div>
)
}
const Column = ({children, className, title}) => {
const [, drop] = useDrop({
accept: 'Our first type',
drop: () => ({name: title}),
});
return (
<div ref={drop} className={className}>
{title}
{children}
</div>
)
}
export const App = () => {
const [isFirstColumn, setIsFirstColumn] = useState(true);
const Item = <MovableItem setIsFirstColumn={setIsFirstColumn}/>;
return (
<div className="container">
{/* Wrap components that will be "draggable" and "droppable" */}
<DndProvider backend={HTML5Backend}>
<Column title='Column 1' className='column first-column'>
{isFirstColumn && Item}
</Column>
<Column title='Column 2' className='column second-column'>
{!isFirstColumn && Item}
</Column>
</DndProvider>
</div>
);
}
@wimpykid719
Copy link

wimpykid719 commented Feb 6, 2022

Hi. I tried this code and I could drag column 1 to column 2 but I couldn't drag column2 to column 1 like a gif. It can't be second time to drag. How to fix that?

@wimpykid719
Copy link

wimpykid719 commented Feb 6, 2022

It worked I changed react-dnd-html5 version 15.0.0 to 14.1.0.
react-dnd version 15.0.0 and react-dnd-html5 version 14.1.0 works well.

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