2 years ago
#54822

hossein fti
React based - make a draggable list item without any libraries
I have a to-do list and I want to make it draggable to be able to move list items and resort them if I drop them. I want to do this without any package and library, just want to do it with javascript and HTML, and CSS. I have a Todolist component and a Listitem component.
this is the part of my Todolist component that displays the render method:
render() {
const List = this.state.todolist.map((item) => {
return (
<Listitem
key={item.key}
handleDrag={this.handleDragItem}
>
})
}
<div
id="todoList"
onDragOver={this.handleAllowDrop}
onDrop={this.handleDropItem}
>
{List}
</div>
and here is my drag functions :
handleDragItem = (event) => {
event.dataTransfer.setData("text", event.target.id);
};
handleAllowDrop = (event) => {
event.preventDefault();
};
handleDropItem = (event) => {
event.preventDefault();
const data = event.dataTransfer.getData("text");
event.target.appendChild(document.getElementById(data));
};
and here is my Listitem component:
class ListItem extends Component {
render() {
let isDraggable;
}
return (
<div
draggable={isDraggable}
onDragStart={this.props.handleDrag}
className="listItemContainer"
>
<img
onMouseDown={() => isDraggable= true}
onMouseUp={() => isDraggable= false}
className="dragIcon"
src={draggingIcon}
alt="drag-icon"
/>
<span>
{this.props.content}
</span>
</div>
);
}
}
I have two problems, first one is that I can't reorder and resort the list when one row drags and drop to another part of the list. The second one is that I can't drag my row with a specific part of the row like img tag
I actually want to permit the list items dragged just with the drag icon.
javascript
html
reactjs
sorting
draggable
0 Answers
Your Answer