Parent

Get the Parent component from the package.

import {Parent} from 'react-reparenting';

Setup โš™๏ธ#

The <Parent> component must be the direct parent of the children which can be transferred. You also have to access the internal parent instance to use the send method.

<Parent parentRef={parentRef}>{children}</Parent>

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 <Parent>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} />),
};
// Parent instance refs.
const parentARef = useRef();
const parentBRef = useRef();
return (
<>
{/* Parent A */}
<div className="parent">
<Parent parentRef={parentARef}>{children.parentA}</Parent>
</div>
{/* Parent B */}
<div className="parent">
<Parent parentRef={parentBRef}>{children.parentB}</Parent>
</div>
</>
);
};

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

const parentA = parentARef.current;
const parentB = parentBRef.current;
// Send the first Child ('c3') of 'parentB'
// before the Child ('c2') of 'parentA'.
parentB.sendChild(parentA, 0, 'c2');
// Send the Child ('c1') of 'parentA'
// in the first position of 'parentB'.
parentA.sendChild(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 ๐Ÿ’ก#

Work in progress.