createParent

Get the createParent method from the package.

import {createParent} from 'react-reparenting';

Setup โš™๏ธ#

You can generate a parent instance to use the send method within a class component. That component must be the direct parent of the children which can be transferred. createParent must be called in the constructor.

class Parent extends React.Component {
constructor(props) {
super(props);
// set the parent in the constructor.
this.parent = createParent(this);
}
render() {
// Render the children directly.
return this.props.children;
}
}

If you want to use another component as parent, you can provide a function that defines that component (You need to know the structure of the React fibers).

class Parent extends React.Component {
constructor(props) {
super(props);
// Select the first child as parent (the div element).
this.parent = createParent(this, (fiber) => fiber.child);
}
render() {
const {children} = this.props;
// Use a different parent.
return <div className="parent">{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.