Created
January 6, 2023 02:31
-
-
Save Phryxia/bacd098470724c78cd0d6141c80a43c6 to your computer and use it in GitHub Desktop.
Typescript React custom confirm alert hook using Promise
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// You need to hook based modal system. If it's not, you may tweak upon your system. | |
import { useModal } from './ModalProvider' | |
export interface UseConfirmOptions { | |
title: string | |
confirmText: string | |
cancelText: string | |
} | |
export function useConfirm(props: UseConfirmOptions) { | |
const { openModal, closeModal } = useModal() | |
return async () => | |
new Promise<boolean>((resolve) => { | |
function createHandler(isConfirmed: boolean) { | |
return () => { | |
closeModal() | |
resolve(isConfirmed) | |
} | |
} | |
openModal({ | |
...props, | |
onConfirm: createHandler(true), | |
onCancel: createHandler(false), | |
}) | |
}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
General
There are some cases when HTML5
<dialog>
can't be applied, especially you have to handle legacy browsers or working with legacy project. In that case, you easily get annoyed when UI designer requests some custom confirm modal.By using our powerful JavaScript feature
Promise
, this can be very effectively solved. If you tweak properly you can make customprompt
oralert
similar to native browser api.Usage
This snippet is very differ to your own system. There are tons of modal system, so you have to apply this upon yours .
Also please checkout this demo.