There are many Libraries you can find out there for drag and drop, But ... most of these libraries are made for lists! So? What's wrong with lists well they are great for sortable lists, like the todo apps where you have a bunch of lists where you can move them in a two-dimensional drag and drop grid meaning you can move things up and down or right and up:(.
In this blog I'm going to show you how to move things Dynamically meaning moving vertically in a list so we can transfer them to a different list or column!
lets go!
the library that I found is "https://github.com/clauderic/react-sortable-hoc"
with this library, you can drag and drop horizontally or vertically or in a grid and sort it in the way you want:)!
if you look at the Link you will see a sortable item component and a sortable list, we will wrap the sortable list in a sort of container and we wrap the sortable item in sortable elements! also, you will see sorted! what's that?
well, when we move things around we are changing the order of their states too:S
so this will update the state to show which element is in which state.
well we have the time to go step by step...and here we go:
1.
$ npm install react-sortable-hoc --save
2.now import it in your file
import {SortableContainer} from "react-sortable-hoc";
- a tip before the next step if you have a list of items like boxes probably you have the items too which you were mapping through the boxes, at this point, I will make them two separate files like a dragBoxList and drag box!
4.inside your dragBoxList we will need the :
const DragBoxList = SortableContainer(({boxes, removeBoxes})) => { return()
- the remove boxes was just an option if you want to delete or remove the boxes.
- so now our dragBoxList is just a reference to the component that is wrapped into the portable container.
We are not done yet! we need to go to our drag box and make it a sortable element.
7.so in your drag box file we will import:
import {SortableElement } from "react-sortable-hoc";
- again the 4th step:
const DragBox = SortableElement(props => { return()}
Now the drag works but still not ready. you can drag it but the drop still needs work since we didn't teach the box how to work;). In docs, we can see in sortableList every element needs a index. index={index} When mapping through your items or boxes:
9.
{boxes.map((box, i) => (
<DragBox
index={i}
key={box.name}
/>
);
}
10.now we have vertical drag and it's not saving the changes.
let's specify axis="XY"
now we have drag vertical and horizontal still no save.
The LAST PIECE!
in the docs, there is onSortEnd that you can copy and paste with the new index and all stuff no need to bind because its using class property syntax, old index, and a new index.
I hope now you can Drag and Drop:D
Top comments (0)