Skip to content

Instantly share code, notes, and snippets.

@RStankov
Created August 15, 2017 12:51
Show Gist options
  • Save RStankov/2504dab6265e73a90c5a1cd4ffde2e3b to your computer and use it in GitHub Desktop.
Save RStankov/2504dab6265e73a90c5a1cd4ffde2e3b to your computer and use it in GitHub Desktop.
import withModal from 'withModal';
function MyPage({ openModal, closeModal }) {
const onClick = () => openModal(<div>Modal content. <button onClick={this.closeModal}>close</button></div>);
return (
<p>
<h1>Title</h1>
<button onClick={onClick}>open modal</button>
</p>
);
}
export default withModal(MyPage);
export default function withModal(component) => {
return class withModal extends React.Component {
static displayName = `withModal(${component.displayName || component.name || 'Component'})`;
state = { modal: null };
render() {
if (this.state.modal) {
return (
<div>
{this.renderComponent()}
<Modal isOpen={true}>{this.state.modal}</Modal>
</div>
);
}
return this.renderComponent();
}
renderComponent() {
return React.createElement(component, { ...this.props, openModal: this.openModal, closeModal: this.closeModal });
}
closeModal = () => {
this.setState({ modal: null });
};
openModal = (modal) => {
this.setState({ modal });
};
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment