'Where to write the logic for drag and drop functionality in React?
I am writing an application similar to Trello for project management. I want to implement the drag and drop functionality from scratch. ( I know there are other libraries already made for this but I want to customize the behavior )
My simplified components look something like this:
import React, { useState } from "react";
const ListsContainer = () => {
const [data, setData] = useState([]);
//fetch data and do stuff on it
return (
<div className="lists-container">
{data.forEach((element) => {
return <List element={element}/>;
})}
</div>
);
};
export default ListsContainer;
import React from "react";
const List = ({ element }) => {
//display stuff about the list
return <div className="list"></div>;
};
export default List;
What I want to do is to be able to click on a List, drag it around inside the ListContainer and drop it in place of another. The problem is that I am unsure of where should I write the logic for this functionality. Right now I see 2 possibilities:
- Have the logic in the
ListContainercomponent. TheListcomponent would be wrapped usingReact.forwardRef()and the container would have the references to all theListcomponents. This makes sense because the data is part of this component and the<div className = "lists-container"></div>is needed in order to calculate if I dropped aListin a different spot and the order between them needs to change. - Have the logic in the
Listcomponent. This just feels more natural. The "drag and drop" functionality is specific to theListand it feels like this is the place where the logic should stay. The problem here would be the fact that I have to pass the data as well as a ref to<div className = "lists-container"></div>fromListContainerdown to eachListin order to determine from inside theListitself whether or not I dropped it in place of another.
There is also most likely a third option to do a combination of these two but I am not 100% sure how to go about it.
So what do you think the best approach is?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
