Skip to content

Instantly share code, notes, and snippets.

@Phryxia
Created January 6, 2023 02:31
Show Gist options
  • Save Phryxia/bacd098470724c78cd0d6141c80a43c6 to your computer and use it in GitHub Desktop.
Save Phryxia/bacd098470724c78cd0d6141c80a43c6 to your computer and use it in GitHub Desktop.
Typescript React custom confirm alert hook using Promise
// 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),
})
})
}
@Phryxia
Copy link
Author

Phryxia commented Jan 6, 2023

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 custom prompt or alert 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.

function Component() {
  const openConfirm = useConfirm({
    title: 'Do you really want to proceed?',
    confirmText: 'proceed',
    cancelText: 'cancel',
  })

  async function handleClick() {
    if (await openConfirm()) {
      // do something
    }
  }

  return <button>Click Me!</button>
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment