useParent

Get the useParent hook from the package.

import {useParent} from 'react-reparenting';

Setup โš™๏ธ#

You can generate a parent instance to use the send method within a function component. You must set the ref in the DOM element which is the direct parent of the children which can be transferred.

const Parent = ({children}) => {
const ref = useRef();
const parent = useParent(ref);
return (
<div className="parent" ref={ref}>
{children}
</div>
);
};

Usage ๐Ÿ“–#

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

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

We use two <Parent> components in the app as defined above.

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 */}
<Parent>{children.parentA}</Parent>
{/* Parent B */}
<Parent>{children.parentB}</Parent>
</>
);
};

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

// 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.