1.0.6 • Published 9 months ago

mui-use-dialogs v1.0.6

Weekly downloads
-
License
MIT
Repository
github
Last release
9 months ago

mui-use-dialogs GitHub license npm version

This package provides basic and common dialogs to be used with @mui/material!

Installation

npm install --save mui-use-dialogs

Demo

Edit mui-use-dialogs demo

Usage

Setup DialogProvider

Wrap your app inside the DialogProvider component.

Note: If you're using Material UI ThemeProvider, make sure DialogProvider is a child of it.

import React from "react";
import { DialogProvider } from "mui-use-dialogs";

const App = () => {
  return (
    <DialogProvider>
      {/* your app... */}
    </DialogProvider>;
  )
};

export default App;

Import a Dialog

You can import whichever dialog hook you wish to use from mui-use-dialogs.

The hooks currently available are:

  • useConfirm
  • usePrompt

Note: These hooks return promises to allow you to use async/await.

See the example below or the demo on CodeSandbox on how to use one of these dialog hooks:

import React from "react";
import Button from "@mui/material/Button";
import { useConfirm } from "material-ui-confirm";

const MyComponent = () => {
    const confirmAsync = useConfirm();

    const handleClick = async () => {
        const confirmed = await confirmAsync(
            "Are you sure?" 
            /*, { ...options }*/,
        );

        if (!confirmed) return;
        console.log("The user has confirmed!");
    };

    return <Button onClick={handleClick}>Click</Button>;
};

export default MyComponent;

Specifying Options

This library provides several way to specify the options for your dialog.

These methods are as follows:

  • Within DialogProvider
  • Within the hook itself (ex. useConfirm/usePrompt)
  • Within the function call (ex. confirm(message, options))

DialogProvider

You may change the default options for dialogs at the DialogProvider level.\ This will result in any hooks within that provider inheriting these options.

const App = () => {
  return (
    <DialogProvider
        prompt={ /* options for usePrompt */}
        confirm={ /* options for useConfirm */}>
      {/* your app... */}
    </DialogProvider>;
  )
};

The Hook (useConfirm/usePrompt)

You may also specify default options within the hook function for the dialogs.

import { useConfirm } from "mui-use-dialogs";

const MyComponent = () => {
    const confirmAsync = useConfirm({
        /* options */
    });
};

The Hook Function

Additionally, you may specify options within the returned function of The Hook.

import { useConfirm } from "mui-use-dialogs";

const MyComponent = () => {
    const confirmAsync = useConfirm();

    const handleClick = async () => {
        const confirmed = await confirmAsync("Are you sure?", {
            /* options */
        });
    };
};

Components & Props

DialogProvider

This component is required in order to render a dialog in the component tree.

NameTypeDefaultDescription
confirmobject{}Overrides the default options used by useConfirm
promptobject{}Overrides the default options used by usePrompt

Common Options

NameTypeDefaultDescription
titlestring?VariesDialog title text.
labelstring?VariesDialog label text.
rejectOnCancelbooleantrueThrow an exception on cancel/close.
autoFocusbooleantrueAuto-focus the dialog.
allowClosebooleanfalseAllow the user to close the dialog
closeButtonShowbooleantrueShow/hide the Close button
closeButtonTextstring?'Close'Text of the Close Button
closeButtonIconReactNode?CloseIcon @mui/icons-material/CloseIcon used for the Close Button
slotPropsSlotPropsType{}Icon used for the Close Button

SlotPropsType

NameTypeDescription
dialogPartial<DialogProps>Override props for <Dialog>
dialogTitlePartial<DialogTitleProps>Override props for <DialogTitle>
dialogContentPartial<DialogContentProps>Override props for <DialogContent>
dialogActionsPartial<DialogActionsProps>Override props for <DialogActions>
closeButtonPartial<ButtonProps>Override props for the Close <Button>

useConfirm(message [, options]) => Promise<bool>

This function opens a confirmation dialog and returns a promise representing the user choice (resolved on confirmation and rejected on cancellation).

Confirm Options

NameTypeDefaultDescription
titlestringConfirmDialog title text.
messagestring'Are you sure?'Confirmation message displayed. Overrides label
yesButtonTextstring'OK'Text shown for the Confirm Button.
yesButtonIconReactNode?Check @mui/icons-material/CheckIcon in the Confirm Button.

Slot Props

NameTypeDefault -Description
messagePartial<DialogContentTextProps>{}Props for the dialog message
yesButtonPartial<ButtonProps>{}Props for the Confirm Button

usePrompt(message [, options]) => Promise<string | null>

This function opens a prompt dialog and returns a promise representing the user text (resolved on OK and rejected on Close).

Prompt Options

NameTypeDefaultDescription
titlestringPromptDialog title text.
defaultTextstringundefinedDefault text shown in the text field.
saveButtonTextstring'OK'Text shown for the Save Button.
saveButtonIconReactNode?Save @mui/icons-material/SaveIcon in the Save Button.
saveOnEnterbooleantrueSave the prompt on Enter key
multilinebooleanfalseWhether or not the text field should allow/show multiple lines.
minRowsnumberCheckMinimum number of rows for the text field. Only used when multiline is `true.
maxRowsnumberundefinedMaximum number of rows for the text field. Only used when multiline is `true.

Slot Props

NameTypeDefault -Description
messagePartial<DialogContentTextProps>{}Props for the dialog message
yesButtonPartial<ButtonProps>{}Props for the Confirm Button

rejectOnCancel

The rejectOnCancel prop is a little special! This prop determines the behavior for when a user clicks Close/Cancel/Whatever.

When rejectOnCancel is TRUE, an error will be thrown. Due to this, you will need to wrap The Hook Function in a try-catch block.

useConfirm with rejectOnCancel=true

import { useConfirm } from "mui-use-dialogs";

const Component = () => {
    const confirmAsync = useConfirm({ rejectOnCancel: true });

    const handleClick = async () => {
        try {
            // No need to use a variable since `confirm` will just throw an exception on fail..
            await confirmAsync("Are you sure?");

            // Confirmed! No error was thrown.
            console.log("The user confirmed!");
        } catch (error) {
            // NOT confirmed
            console.log("The user did not confirm!");
        }
    }
}

useConfirm with rejectOnCancel=false

import { useConfirm } from "mui-use-dialogs";

const Component = () => {
    const confirmAsync = useConfirm({ rejectOnCancel: false });

    const handleClick = async () => {
        // No need for a try-catch block since no exception will be thrown!
        // Need to use a variable to check the `confirm` response.
        const confirmed = await confirmAsync("Are you sure?");
        if (confirmed) {
            // Confirmed!
            console.log("The user confirmed!");
        } else {
            // NOT confirmed
            console.log("The user did not confirm!");
        }
    }
}

usePrompt with rejectOnCancel=true

import { usePrompt } from "mui-use-dialogs";

const Component = () => {
    const promptAsync = usePrompt({ rejectOnCancel: true });

    const handlePrompt = async () => {
        try {
            // Need to use a try-catch as an error will be thrown if "Cancel" is clicked.
            // No need to use a variable since `confirm` will just throw an exception on fail..
            const userPrompt = await promptAsync("Enter a prompt...");
            console.log(`The user entered the prompt: ${userPrompt}`);
        } catch (error) {
            // User closed out of the dialog.. Did not click "OK"
            console.log("The user cancelled out of the dialog...");
        }
    }
}

usePrompt with rejectOnCancel=false

import { usePrompt } from "mui-use-dialogs";

const Component = () => {
    const promptAsync = usePrompt({ rejectOnCancel: false });

    const handlePrompt = async () => {
        // No need for a try-catch!
        const userPrompt = await promptAsync ("Enter a prompt...");
        if(typeof userPrompt === "string"){
            console.log(`The user entered the prompt: ${userPrompt}`);
        } else { 
            // The user clicked Cancel
        }
    }
    // ...
}

Credits

This package was heavily based on jonatanklosko's material-ui-confirm. This package simply adds some more features.

1.0.6

9 months ago

1.0.5

10 months ago

1.0.4

10 months ago

1.0.3

10 months ago

1.0.2

10 months ago

1.0.1

10 months ago

1.0.0

10 months ago