'React Drag & Drop Using References to Components

I'm working on a React project, and I'd like to be able to load a component after dragging and dropping a reference to it. For example, on the left side of the screen I have a list of components, just names, not the actual components (barchart, linechart etc), and I'd like to be able to drag the name into another area of the screen and have that component load there. So far I've been able to transfer the list item itself using e.dataTransfer.setData / getData, but I'm not sure how to load the component that the list item is referencing. Any ideas how to do this?

Thanks!



Solution 1:[1]

You could use a your list of components (not actual) store its identifiers (strings, ids) and when you drop each component into the drop zone, you could write a conditional rendering inside that drop zone (ex: drop zone has an array from state, when array has new element, render that element according to its identifier)

Solution 2:[2]

You're not saying if you're transfering:

  • a reference to the component class (or function)
  • a reference to component instance

If the reference is to a component class:
(please note, that this is only an approximate pseudo code)

const onDropped = () => {
    const myDroppedRef = getData();
    setAllDroppedItems((current) => ([
        ...current,
        <myDroppedRef ...some props />,
    ]));
};

const [allDroppedItems, setAllDroppedItems] = useState([]);

return (<div>
    {allDroppedItems}
</div>
);

If the reference is to an instance of a component,
the example is the same, except for this:

        // change this:
        <myDroppedRef ...some props />,

        // to this:
        myDroppedRef,

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Viet
Solution 2 Vaz