Reparentable

Import the createReparentableSpace method from the package.

import {createReparentableSpace} from 'react-reparenting';

Setup โš™๏ธ#

First you need to define a Space that will virtually contain the components. Only <Reparentable>s belonging to the same space can send children to each other.

const {Reparentable, sendReparentableChild} = createReparentableSpace();

The <Reparentable> must be the direct parent of the children which can be transferred, and it must have an unique id that differentiates it from other <Reparentable>s in its Space.

<Reparentable id="id">{children}</Reparentable>

Usage ๐Ÿ“–#

Let's define a very simple child component for the example.

const Child = () => <div />;

We define in our app two simple parent components, and insert within them the <Reparentable>s.

const App = () => {
// The Parents.
const [parents, setParents] = useState({
A: ['c1', 'c2'],
B: ['c3'],
});
// The Child components.
const children = {
parentA: parents.A.map((key) => <Child key={key} />),
parentB: parents.B.map((key) => <Child key={key} />),
};
return (
<>
{/* Parent A */}
<div className="parent">
<Reparentable id="parentA">{children.parentA}</Reparentable>
</div>
{/* Parent B */}
<div className="parent">
<Reparentable id="parentB">{children.parentB}</Reparentable>
</div>
</>
);
};

Now we can reparent anywhere in our app using the sendReparentableChild method.

// Send the first Child ('c3') of 'parentB'
// before the Child ('c2') of 'parentA'.
sendReparentableChild('parentB', 'parentA', 0, 'c2');
// Send the Child ('c1') of 'parentA'
// in the first position of 'parentB'.
sendReparentableChild('parentA', 'parentB', 'c1', 0);
// Re-render the components with the changes.
// The transferred children won't be re-mounted.
setParents({
A: ['c3', 'c2'],
B: ['c1'],
});

Example ๐Ÿ’ก#

Check out the full example on codesandbox.