Skip to content

Instantly share code, notes, and snippets.

@cdosborn
Last active April 20, 2017 23:43
Show Gist options
  • Save cdosborn/634a4cde6eadf21583ddcea80d2778f5 to your computer and use it in GitHub Desktop.
Save cdosborn/634a4cde6eadf21583ddcea80d2778f5 to your computer and use it in GitHub Desktop.
function hideable(instance, isHidden) {
const HideableComponent = React.createClass({
render() {
if (isHidden) {
return null;
}
return React.cloneElement(instance, this.props);
}
});
return persistable(<HideableComponent />);
}
const PersistentComponent = React.createClass({
propTypes: {
instance: React.PropTypes.element.isRequired
},
getInitialState() {
return {
state: null
}
},
snapshot(state) {
this.setState({ state: state });
},
restore(callback) {
if (this.state.state) {
callback(this.state.state);
return true;
} else {
return false;
}
},
render() {
return React.cloneElement(this.props.instance, {
snapshot: this.snapshot,
restore: this.restore,
});
}
})
function persistable(instance) {
return <PersistentComponent instance={instance}/>;
}
const View = React.createClass({
propTypes: {
restore: React.PropTypes.func,
snapshot: React.PropTypes.func,
},
getInitialState: function() {
return {
// ...
};
},
componentDidMount() {
if (this.props.restore) {
this.props.restore((state) => {
this.setState(state);
});
}
},
componentWillUnmount() {
if (this.props.snapshot) {
this.props.snapshot(this.state);
}
},
render: function() {
// ...
}
});
// hideable(<View />, true /* true if it should be hidden */)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment