Confirming user choice is a good thing to do, it should also be easy to do.
This package provides simple confirmation dialogs built on top of @mui/material and straightforward to use thanks to React Hooks.
npm install --save material-ui-confirmWrap your app inside the ConfirmProvider component.
Note: If you're using Material UI ThemeProvider, make sure ConfirmProvider is a child of it.
import React from 'react';
import { ConfirmProvider } from 'material-ui-confirm';
const App = () => {
return (
<ConfirmProvider>
{/* ... */}
</ConfirmProvider>
);
};
export default App;Call the useConfirm hook wherever you need the confirm function.
Note: A component calling useConfirm must be a child of ConfirmProvider.
import React from 'react';
import Button from '@mui/material/Button';
import { useConfirm } from 'material-ui-confirm';
const Item = () => {
const confirm = useConfirm();
const handleClick = () => {
confirm({ description: 'This action is permanent!' })
.then(() => { /* ... */ })
.catch(() => { /* ... */ });
};
return (
<Button onClick={handleClick}>
Click
</Button>
);
};
export default Item;This component is required in order to render a dialog in the component tree.
| Name | Type | Default | Description |
|---|---|---|---|
defaultOptions |
object |
{} |
Overrides the default options used by confirm. |
This hook returns the confirm function.
This function opens a confirmation dialog and returns a promise representing the user choice (resolved on confirmation and rejected on cancellation).
| Name | Type | Default | Description |
|---|---|---|---|
title |
ReactNode |
'Are you sure?' |
Dialog title. |
description |
ReactNode |
'' |
Dialog content, automatically wrapped in DialogContentText. |
content |
`ReactNode | null` | null |
confirmationText |
ReactNode |
'Ok' |
Confirmation button caption. |
cancellationText |
ReactNode |
'Cancel' |
Cancellation button caption. |
dialogProps |
object |
{} |
Material-UI Dialog props. |
confirmationButtonProps |
object |
{} |
Material-UI Button props for the confirmation button. |
cancellationButtonProps |
object |
{} |
Material-UI Button props for the cancellation button. |
You can get this behavior by adding the autoFocus property to the confirmation button.
This way the button is focused as soon as the dialog opens and hitting Enter
naturally triggers a click.
const MyComponent = () => {
// ...
const handleClick = () => {
confirm({ confirmationButtonProps: { autoFocus: true } })
.then(() => { /* ... */ })
.catch(() => { /* ... */ });
};
// ...
};const App = () => {
return (
<ConfirmProvider
defaultOptions={{
confirmationButtonProps: { autoFocus: true }
}}
>
{/* ... */}
</ConfirmProvider>
);
};