material-ui-confirm

repository·master·Indexed 18 days ago

https://github.com/jonatanklosko/material-ui-confirm

A library for creating simple confirmation dialogs built on top of @mui/material. It provides a ConfirmProvider for context and a useConfirm hook to trigger dialogs programmatically, returning a Promise that resolves to a ConfirmResult object containing the user's choice and the reason for closure.

Tokens
4.4K
Snippets
10
Records
12
Agent score
63%

What's inside material-ui-confirm

  1. Enable confirmation by pressing Enter

    master

    To allow users to confirm the dialog by pressing the Enter key, you must set the autoFocus property on the confirmation button. This can be done locally for a specific call or globally via ConfirmProvider.

    // Locally
    const handleClick = async () => {
      const { confirmed } = await confirm({
        confirmationButtonProps: { autoFocus: true },
      });
    
      if (confirmed) {
        /* ... */
      }
    };
    
    // Globally
    const App = () => {
      return (
        <ConfirmProvider
          defaultOptions={{
            confirmationButtonProps: { autoFocus: true },
          }}
        >
          {/* ... */}
        </ConfirmProvider>
      );
    };
  2. Set up the ConfirmProvider

    master

    To use the confirmation dialogs, you must wrap your application (or the relevant part of your component tree) in the ConfirmProvider component.

    Important: If you are using a Material UI ThemeProvider, ensure that ConfirmProvider is a child of the ThemeProvider so that the dialogs inherit your theme settings.

    import React from "react";
    import { ConfirmProvider } from "material-ui-confirm";
    
    const App = () => {
      return <ConfirmProvider>{/* ... */}</ConfirmProvider>;
    };
    
    export default App;
  3. Understand the ConfirmResult object

    master

    The ConfirmResult object is returned by the confirm function and the useConfirm hook once the dialog is resolved. It contains two fields:

    • confirmed: boolean - Indicates if the user confirmed the action.
    • reason: 'confirm' | 'cancel' | 'natural' | 'unmount' - Explains why the dialog resolved.
      • confirm: User clicked the confirmation button.
      • cancel: User clicked the cancellation button.
      • natural: The dialog was closed via a method other than the explicit buttons (e.g., clicking backdrop if allowed).
      • unmount: The component triggering the dialog was unmounted.
  4. Use the useConfirm hook to trigger dialogs

    master

    The useConfirm hook provides the confirm function. Any component calling useConfirm must be a descendant of ConfirmProvider in the component tree.

    When you call confirm(options), it returns a Promise that resolves to an object containing the user's choice and the reason for the closure.

    import React from "react";
    import Button from "@mui/material/Button";
    import { useConfirm } from "material-ui-confirm";
    
    const Item = () => {
      const confirm = useConfirm();
    
      const handleClick = async () => {
        const { confirmed, reason } = await confirm({
          description: "This action is permanent!",
        });
    
        if (confirmed) {
          /* ... */
        }
    
        console.log(reason);
        //=> "confirm" | "cancel" | "natural" | "unmount"
      };
    
      return <Button onClick={handleClick}>Click</Button>;
    };
    
    export default Item;
  5. ConfirmProvider Props Reference

    master

    The ConfirmProvider component is required to render the dialog in the component tree. It accepts the following props:

    | Name                  | Type      | Default | Description |
    | --------------------- | --------- | ------- | ----------- |
    | **`defaultOptions`**  | `object`  | `{}`    | Overrides the default options used by `confirm`. |
    | **`useLegacyReturn`** | `boolean` | `false` | When set to `true`, restores the `confirm` behaviour from v3: the returned promise is resolved on confirm, rejected on cancel, and kept pending on natural close. |
  6. confirm() function options reference

    master

    The confirm function accepts an optional options object to customize the dialog appearance and behavior.

    Return Value: Promise<{ confirmed: boolean; reason: "confirm" | "cancel" | "natural" | "unmount"; }>

    | Name                                       | Type        | Default                 | Description |
    | ------------------------------------------ | ----------- | ----------------------- | ----------- |
    | **`title`**                                | `ReactNode` | `'Are you sure?'`       | Dialog title. |
    | **`description`**                          | `ReactNode` | `''`                    | Dialog content, automatically wrapped in `DialogContentText`. |
    | **`content`**                              | `ReactNode` | `null`                  | Dialog content, same as `description` but not wrapped in `DialogContentText`. Supersedes `description` if present. |
    | **`confirmationText`**                     | `ReactNode` | `'Ok'`                  | Confirmation button caption. |
    | **`cancellationText`**                     | `ReactNode` | `'Cancel'`              | Cancellation button caption. |
    | **`dialogProps`**                          | `object`    | `{}`                    | Material-UI [Dialog](https://mui.com/material-ui/api/dialog/#props) props. |
    | **`dialogActionsProps`**                   | `object`    | `{}`                    | Material-UI [DialogActions](https://mui.com/material-ui/api/dialog-actions/#props) props. |
    | **`confirmationButtonProps`**              | `object`    | `{}`                    | Material-UI [Button](https://mui.com/material-ui/api/button/#props) props for the confirmation button. |
    | **`cancellationButtonProps`**              | `object`    | `{}`                    | Material-UI [Button](https://mui.com/material-ui/api/dialog/#props) props for the cancellation button. |
    | **`titleProps`**                           | `object`    | `{}`                    | Material-UI [DialogTitle](https://mui.com/api/dialog-title/#props) props for the dialog title. |
    | **`contentProps`**                         | `object`    | `{}`                    | Material-UI [DialogContent](https://mui.com/api/dialog-content/#props) props for the dialog content. |
    | **`allowClose`**                           | `boolean`   | `true`                  | Whether natural close (escape or backdrop click) should close the dialog. When set to `false` force the user to either cancel or confirm explicitly. |
    | **`confirmationKeyword`**                  | `string`    | `undefined`             | If provided the confirmation button will be disabled by default and an additional textfield will be rendered. The confirmation button will only be enabled when the contents of the textfield match the value of `confirmationKeyword` |
    | **`confirmationKeywordTextFieldProps`**    | `object`    | `{}`                    | Material-UI [TextField](https://mui.com/material-ui/api/text-field/) props for the confirmation keyword textfield. |
    | **`acknowledgement`**                       | `string`    | `undefined`             | If provided shows the acknowledge checkbox with this string as checkbox label and disables the confirm button while the checkbox is unchecked. |
    | **`acknowledgementFormControlLabelProps`** | `object`    | `{}`                    | Material-UI [FormControlLabel](https://mui.com/material-ui/api/form-control-label/#props) props for the form control label. |
    | **`acknowledgementCheckboxProps`**          | `object`    | `{}`                    | Material-UI [Checkbox](https://mui.com/material-ui/api/checkbox/#props) props for the acknowledge checkbox. |
    | **`hideCancelButton`**                     | `boolean`   | `false`                 | Whether to hide the cancel button. |
    | **`buttonOrder`**                          | `string[]`  | `["cancel", "confirm"]` | Specify the order of confirm and cancel buttons. |
  7. Configure the ConfirmProvider

    master

    The ConfirmProvider component must wrap your application (or the part of the application using the confirm functionality) to provide the context required by the useConfirm hook.

    It accepts the following props:

    • children: The React nodes to be rendered.
    • defaultOptions: An object of type ConfirmOptions to apply default settings to all confirmation dialogs within this provider.
    • useLegacyReturn: A boolean flag to control the return format (see ConfirmResult).
    <ConfirmProvider defaultOptions={{ title: 'Are you sure?' }}>
      <App />
    </ConfirmProvider>
  8. Use ConfirmProvider and useConfirm to trigger confirmation dialogs

    master

    To use the library, you must wrap your application (or a specific part of it) in the ConfirmProvider. This provides the context necessary for the confirmation dialogs to appear. Once wrapped, you can use the useConfirm hook in any child component to trigger a confirmation dialog programmatically.

    import { ConfirmProvider, useConfirm } from 'material-ui-confirm';
    
    function MyComponent() {
      const confirm = useConfirm();
    
      const handleDelete = () => {
        confirm({
          title: 'Confirm Delete',
          content: 'Are you sure you want to delete this item?',
        }).then(() => {
          // User clicked 'OK'
          console.log('Deleted');
        }).catch(() => {
          // User clicked 'Cancel'
          console.log('Cancelled');
        });
      };
    
      return <button onClick={handleDelete}>Delete</button>;
    }
    
    function App() {
      return (
        <ConfirmProvider>
          <MyComponent />
        </ConfirmProvider>
      );
    }
  9. Use the confirm function directly

    master

    The library also exports a confirm function directly. This is typically used in conjunction with the ConfirmProvider context.

    import { confirm } from 'material-ui-confirm';
    
    // Note: This usually requires the ConfirmProvider to be present in the component tree
    confirm({ title: 'Title', content: 'Content' });
  10. Configure confirmation dialogs with ConfirmOptions

    master

    The ConfirmOptions object allows you to customize the appearance and behavior of the confirmation dialog.

    Available options:

    • title: React.ReactNode - The title of the dialog.
    • titleProps: DialogTitleProps - Props passed to the MUI DialogTitle component.
    • description: React.ReactNode - Text describing the action.
    • content: React.ReactNode | null - Additional content inside the dialog.
    • contentProps: DialogContentProps - Props passed to the MUI DialogContent component.
    • confirmationText: React.ReactNode - Text for the confirmation button.
    • cancellationText: React.ReactNode - Text for the cancellation button.
    • dialogProps: Omit<DialogProps, "open"> - Props passed to the MUI Dialog component.
    • dialogActionsProps: DialogActionsProps - Props passed to the MUI DialogActions component.
    • confirmationButtonProps: ButtonProps - Props for the confirmation button.
    • cancellationButtonProps: ButtonProps - Props for the cancellation button.
    • allowClose: boolean - Whether the dialog can be closed (e.g., by clicking backdrop).
    • confirmationKeyword: string - A specific string the user must type to confirm (used with confirmationKeywordTextFieldProps).
    • confirmationKeywordTextFieldProps: TextFieldProps - Props for the text field used for keyword entry.
    • hideCancelButton: boolean - If true, the cancellation button is not rendered.
    • buttonOrder: string[] - Defines the order of buttons.
    • acknowledgement: string - Text for an acknowledgement checkbox.
    • acknowledgementFormControlLabelProps: FormControlLabelProps - Props for the checkbox label.
    • acknowledgementCheckboxProps: CheckboxProps - Props for the checkbox itself.
  11. Use the useConfirm hook

    master

    The useConfirm hook returns a function that, when called, triggers a confirmation dialog. This function returns a Promise that resolves with a ConfirmResult object.

    Signature: const confirm = useConfirm(); confirm(options?: ConfirmOptions): Promise<ConfirmResult>

    Example usage:

    const confirm = useConfirm();
    
    const handleDelete = async () => {
      const { confirmed } = await confirm({ title: 'Delete item?' });
      if (confirmed) {
        // perform deletion
      }
    };
    const confirm = useConfirm();
    const result = await confirm({ title: 'Confirm action' });