Skip to content

Instantly share code, notes, and snippets.

@e1himself
Last active November 21, 2024 23:16
Show Gist options
  • Save e1himself/d2b8acb398a5310cf6b8e27d92429ab7 to your computer and use it in GitHub Desktop.
Save e1himself/d2b8acb398a5310cf6b8e27d92429ab7 to your computer and use it in GitHub Desktop.
The initial implementation of @prezly/react-promise-modal
import ReactDOM from 'react-dom';
import { noop } from 'lodash';
const DEFAULT_OPTIONS = {
destructionDelay: 300,
};
const reactConfirmation = async (renderModal, options = {}) => {
const { destructionDelay } = { ...DEFAULT_OPTIONS, ...options };
const container = document.createElement('div');
document.body.appendChild(container);
const displayModal = (props) => {
ReactDOM.render(renderModal({ ...props, show: true }), container);
};
const hideModal = (props, callback) => {
ReactDOM.render(renderModal({ ...props, show: false }), container, callback);
};
const destroyModal = () => {
ReactDOM.unmountComponentAtNode(container);
document.body.removeChild(container);
};
const confirmation = new Promise((resolve) => {
const onConfirm = () => resolve(true);
const onCancel = () => resolve(false);
displayModal({ onConfirm, onCancel });
});
try {
return await confirmation;
} finally {
const onConfirm = noop;
const onCancel = noop;
hideModal({ onConfirm, onCancel }, () => {
setTimeout(destroyModal, destructionDelay);
});
}
};
export default reactConfirmation;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment