Minimal Customizable Confirm Dialog Hook For React – useConfirm

Description:

The useConfirm provides a custom React component to create minimal yet customizable confirm dialog boxes in your React apps. It’s a great alternative to browser’s native window.confirm popup.

How to use it:

1. Install & download.

# NPM
$ npm install use-confirm-hook
# BUN
$ bun add use-confirm-hook

2. Create a custom confirm component in ‘confirm-dialog.tsx’.

import { useConfirm } from "use-confirm-hook";
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
} from "./ui/alert-dialog";
export const ConfirmDialog = () => {
  const { isAsking, message, deny, confirm } = useConfirm();
  return (
    <AlertDialog open={isAsking} onOpenChange={deny}>
      <AlertDialogContent>
        <AlertDialogHeader>
          <AlertDialogTitle>Confirm</AlertDialogTitle>
          <AlertDialogDescription>{message}</AlertDialogDescription>
        </AlertDialogHeader>
        <AlertDialogFooter>
          <AlertDialogCancel onClick={deny}>Cancel</AlertDialogCancel>
          <AlertDialogAction onClick={confirm}>Confirm</AlertDialogAction>
        </AlertDialogFooter>
      </AlertDialogContent>
    </AlertDialog>
  );
};

3. Add the Provider and your React component.

import { UseConfirmProvider } from "use-confirm-hook";
import { ConfirmDialog } from "./confirm-dialog";
import { App } from "./app";
export default function Root() {
  return (
    <UseConfirmProvider>
      <App />
      <ConfirmDialog />
    </UseConfirmProvider>
  );
}

4. Ask the user to confirm an action.

import { useConfirm } from "use-confirm-hook";
export default function Component() {
  const { ask } = useConfirm();
  function handleDelete() {
    const res = await ask("Are you sure?");
    if (res) {
      console.log("continue with deletion");
    } else {
      console.log("don't delete");
    }
  }
  return (
    <div>
      <button onClick={handleDelete}>Delete</button>
    </div>
  );
}

Preview:

Minimal Customizable Confirm Dialog Hook For React

Tags:

Add Comment