I've created a reusable confirm dialog in React. Here is the code:
import { Dialog, DialogTitle, DialogContent, DialogActions, Button, Box, IconButton, Typography, } from '@material-ui/core';
import { Close } from "@material-ui/icons";
import { create } from "zustand"
const useConfirmDialogStore = create((set) => ({
message: "",
onSubmit: undefined,
close: () => set({ onSubmit: undefined }),
}));
const ConfirmDialog = () => {
const { message, onSubmit, close } = useConfirmDialogStore();
return (
<Dialog open={Boolean(onSubmit)} onClose={close} maxWidth="sm" fullWidth>
<DialogTitle>Confirm the action</DialogTitle>
<Box position="absolute" top={0} right={0}>
<IconButton onClick={close}>
<Close />
</IconButton>
</Box>
<DialogContent>
<Typography>{message}</Typography>
</DialogContent>
<DialogActions>
<Button color="primary" variant="contained" onClick={close}>
Cancel
</Button>
<Button
color="secondary"
variant="contained"
onClick={() => {
if (onSubmit) {
onSubmit();
}
close();
}}
>
Confirm
</Button>
</DialogActions>
</Dialog>
);
};
export const confirmDialog = (message, onSubmit) => {
console.log('yo'); //this text is logged in console on button click
useConfirmDialogStore.setState({
message,
onSubmit,
});
};
export default ConfirmDialog;
In my other component I want to show this generic modal/dialog on button click:
<DeleteIcon
onClick={() => {
confirmDialog(
"Do you really want to delete all the data?",
() => console.log("deleting all the data!")
);}}>
Edit
</DeleteIcon>
But the dialog is never being shown. I've added console.log
part in export const confirmDialog
just to see if it's being called at all and seems like it's logging in console. Does anyone know what could be the missing part to show the dialog?
it seems that you didn't add the ConfirmDialog component to your main component tree. Include the ConfirmDialog component somewhere.
for example, in your main component App.js import ConfirmDialog from "./ConfirmDialog";