R
R
RusTorg2018-07-10 02:42:38
JavaScript
RusTorg, 2018-07-10 02:42:38

What is the best way to organize DnD tree categories in React?

How can I organize a tree view of elements with drag-and-drop in react?
As an example, the menu editor in WP:
ngmdvjkyo21xcrum7bk6ez6tqpq.gif
I tried to implement tree-like myself through the react-beautiful-dnd library , it allows you to drag components between spaces (several areas with elements of the same type) but does not support nesting of DragDropContexts, which is why the capture of the dragged area does not work properly and styles are not updated on the dragged element (An example of how react-beautiful-dnd can't work with codesandbox.io nesting .).

Answer the question

In order to leave comments, you need to log in

2 answer(s)
R
RusTorg, 2018-07-10
@RusTorg

react-sortable-tree

S
Sergey Suntsev, 2018-07-10
@GreyCrew

I would divide the task into several actions, first I would form a data model, as I understand it will be a tree, and to work with it I would make a bypass function, modernizing which I would be able to operate on data at the model level.
The data model can be formed both flat (key-value and parent ID) and deep, I like deep ones.
Reading from such a model might look something like this:

export const getObjects = (obj, key, val) => {
  let objects = []
  for (let i in obj) {
    if (!obj.hasOwnProperty(i)) continue
    if (typeof obj[i] == 'object') {
      objects = objects.concat(getObjects(obj[i], key, val))
    } else if (i == key && obj[key] == val) {
      objects.push(obj)
    }
  }
  return objects
}

Next, I would create a ui component to which I passed the object, in it I connected some kind of DnD library
like this
one . In fact, this is not as difficult as it seems, you just need to determine the current nesting of the element being edited

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question