ghostman231111
ghostman231111

Reputation: 13

Using React DND to drag component

I'm trying to implement the drag and replace functionality using react dnd.

const [components, setComponents] = useState([
    { id: "one", cmp: "StatsTiles", title: "StatsTiles", order: 2 },
    {
      id: "two",
      cmp: "DeveloperProfile",
      title: `DeveloperProfile`,
      order: 3,
    },
  ]);  

I have two component StatsTiles and DeveloperProfile which I want to switch position whenever I drag any particular component and hover over other component.

  {components
              .sort((a, b) => {
                let keyA = a.order,
                  keyB = b.order;
                if (keyA < keyB) return -1;
                if (keyA > keyB) return 1;
                return 0;
              })
              .map(({ id, cmp, title, order }, idx) => {
                const Comp = tilesComponent[cmp];
                return (
                  <div
                    ref={drag}
                    style={{ opacity }}
                    className="row mt-2 w-100"
                  >
                    <Comp />
                  </div>
                );
              })}

This is how I'm rendering the components inside page, My plan is to change the order in react dnd drop function. So the component will change position.

But I'm facing an issue here, Inspect element snapshot

Only one of my element is have draggable attribute I don't know why both are inside map function. All suggestions are welcome

Upvotes: 0

Views: 2117

Answers (1)

Nausif Momin
Nausif Momin

Reputation: 37

I think this would be helpful for you https://codesandbox.io/s/try06

In the single card, you should move items so try to use it like an example given above.

Upvotes: 0

Related Questions