Skip to content

Instantly share code, notes, and snippets.

@leoasis
Last active June 26, 2017 19:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save leoasis/e1d093141e5f22e4e1e346e6726dfa5b to your computer and use it in GitHub Desktop.
Save leoasis/e1d093141e5f22e4e1e346e6726dfa5b to your computer and use it in GitHub Desktop.
Reparenting a component
import React, { Component } from 'react';
import PropTypes from 'proptypes';
import ReactDOM from 'react-dom';
const store = {};
function getMountNode(uid) {
if (!store[uid]) {
store[uid] = {
mountNode: document.createElement('div'),
inUse: true
};
} else {
store[uid].inUse = true;
}
return store[uid].mountNode;
}
function removeMountNode(uid) {
const record = store[uid];
record.inUse = false;
setTimeout(() => {
if (!store[uid].inUse) {
ReactDOM.unmountComponentAtNode(store[uid].mountNode);
delete store[uid];
}
}, 0);
}
export default class Reparentable extends Component {
static propTypes = {
uid: PropTypes.string.isRequired,
children: PropTypes.element.isRequired
}
componentDidMount() {
const mountNode = getMountNode(this.props.uid);
this.el.appendChild(mountNode);
this.renderChildrenIntoNode(mountNode);
}
componentDidUpdate() {
const mountNode = getMountNode(this.props.uid);
this.renderChildrenIntoNode(mountNode);
}
componentWillUnmount() {
removeMountNode(this.props.uid);
}
renderChildrenIntoNode(node) {
// We use this instead of `render` because this also handles
// passing the context
ReactDOM.unstable_renderSubtreeIntoContainer(this, this.props.children, node);
}
render() {
return <div ref={(el) => { this.el = el; }}></div>;
}
}
<div>
{this.state.showingPage === 'page1' &&
<Page1>
<Reparentable uid="1">
<FooComponent {…someProps} />
</Reparentable>
</Page1>}
{this.state.showingPage === 'page2' &&
<Page2>
<Reparentable uid="1">
<FooComponent {…someOtherProps} />
</Reparentable>
</Page2>}
</div>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment