Skip to content

Instantly share code, notes, and snippets.

@vitalijalbu
Last active May 22, 2024 07:46
Show Gist options
  • Save vitalijalbu/1a62617e022d7b57b50a0dc300c90567 to your computer and use it in GitHub Desktop.
Save vitalijalbu/1a62617e022d7b57b50a0dc300c90567 to your computer and use it in GitHub Desktop.
Chakra UI Dialog Alert Confirm

Chakra UI Dialog Alert Confirm React 18

How to use?

  import { Confirm } from  "../link-to-file";
  
  /* Confirmation Delete */
  const handleDelete = () => {
    Confirm({
      title: "Confirmation delete",
      message: "Are you sure to delete?",
      okText: 'Confirm',
      confirmColor: 'primary',
      onOk() {
        console.log('confirmed');
      },
      onCancel() {
        console.log('closed');
      },
    });
  };

**

Then apply button onClick

**

<Button onClick={handleDelete}>Delete</Button>
import {
AlertDialog,
AlertDialogBody,
AlertDialogCloseButton,
AlertDialogContent,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogOverlay,
Button,
theme,
ThemeProvider,
useDisclosure
} from "@chakra-ui/react";
import React, { useEffect, useRef } from "react";
import ReactDOM from "react-dom/client";
let returnResponse;
const AlertRoot = (props) => {
const { title, message, cancelText, okText, onOk, onCancel } = props;
const { isOpen, onOpen, onClose } = useDisclosure();
const cancelRef = useRef(null);
useEffect(() => {
onOpen();
}, [onOpen]);
const confirm = () => {
onOk();
onClose();
};
const cancel = () => {
onCancel();
onClose();
};
return (
<>
<ThemeProvider theme={theme}>
<AlertDialog
motionPreset="slideInBottom"
leastDestructiveRef={cancelRef}
onClose={onClose}
isOpen={isOpen}
isCentered
>
<AlertDialogOverlay />
<AlertDialogContent>
<AlertDialogHeader fontSize="lg" fontWeight="bold">{title}</AlertDialogHeader>
<AlertDialogCloseButton />
<AlertDialogBody>{message}</AlertDialogBody>
<AlertDialogFooter>
<Button variant="ghost" ref={cancelRef} onClick={cancel}>
{cancelText ?? 'Close'}
</Button>
<Button ml={3} onClick={confirm} colorScheme="red">
{okText ?? 'Continue'}
</Button>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
</ThemeProvider>
</>
);
};
// pass in alert type
function Create(props) {
const rootID = "temp";
let div = document.getElementById(rootID);
if (!div) {
div = document.createElement("div");
div.id = rootID;
document.body.appendChild(div);
}
const root = ReactDOM.createRoot(div);
root.render(<AlertRoot {...props} />);
if (div) {
div.remove();
}
}
export function Confirm(props) {
Create(props);
return new Promise(resolve => {
returnResponse = resolve;
});
}
@mauriciomassaia
Copy link

Hi, thanks for your demo, it works fine but I dont understand why do you need to return a promise and also keep its resolve value saved in a variable. Do you have other examples with a scenario that it would be used?

Cheers

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