### Install material-ui-confirm using npm (Shell)
Source: https://github.com/jonatanklosko/material-ui-confirm/blob/master/README.md
This command installs the material-ui-confirm package using npm. It requires Node.js and npm to be installed on the system. The installation adds the package to the project dependencies, enabling its usage in React applications.
```shell
npm install --save material-ui-confirm
```
--------------------------------
### Setup ConfirmProvider with Material-UI Theme
Source: https://context7.com/jonatanklosko/material-ui-confirm/llms.txt
The ConfirmProvider component wraps your application to enable confirmation dialogs throughout the component tree. It accepts default options for dialogs and should be placed within Material-UI's ThemeProvider.
```jsx
import React from "react";
import { ConfirmProvider } from "material-ui-confirm";
import { ThemeProvider, createTheme } from "@mui/material/styles";
const theme = createTheme();
function App() {
return (
);
}
export default App;
```
--------------------------------
### Advanced Dialog Customization (React/JSX)
Source: https://context7.com/jonatanklosko/material-ui-confirm/llms.txt
Demonstrates customizing the dialog with Material-UI props, styling the title, content, and buttons. This example provides extended control over the appearance and behavior of the confirm dialog using props. Requires `material-ui-confirm` and `@mui/material`.
```jsx
import React from "react";
import Button from "@mui/material/Button";
import { useConfirm } from "material-ui-confirm";
function AdvancedConfirmButton() {
const confirm = useConfirm();
const handleAdvancedConfirm = async () => {
const { confirmed, reason } = await confirm({
title: "Premium Feature",
description: "This feature requires a premium subscription.",
confirmationText: "Upgrade Now",
cancellationText: "Maybe Later",
dialogProps: {
maxWidth: "sm",
fullWidth: true,
sx: {
"& .MuiDialog-paper": {
borderRadius: 3,
padding: 2,
},
},
},
dialogActionsProps: {
sx: {
justifyContent: "space-between",
px: 3,
pb: 2,
},
},
titleProps: {
sx: {
fontSize: "1.5rem",
fontWeight: "bold",
color: "primary.main",
},
},
contentProps: {
sx: {
py: 3,
},
},
confirmationButtonProps: {
variant: "contained",
size: "large",
sx: { px: 4 },
},
cancellationButtonProps: {
variant: "text",
size: "large",
},
});
if (confirmed) {
window.location.href = "/upgrade";
} else {
console.log(`User declined: ${reason}`);
}
};
return ;
}
export default AdvancedConfirmButton;
```
--------------------------------
### Setup ConfirmProvider in React app (JavaScript)
Source: https://github.com/jonatanklosko/material-ui-confirm/blob/master/README.md
This code wraps the React app with the ConfirmProvider component to enable confirmation dialogs. It depends on the material-ui-confirm package and React. The input is the root app component, and it outputs a provider-wrapped app that supports confirm functionality. Note: Ensure ConfirmProvider is a child of Material-UI's ThemeProvider if using theming.
```javascript
import React from "react";
import { ConfirmProvider } from "material-ui-confirm";
const App = () => {
return {/* ... */};
};
export default App;
```
--------------------------------
### Basic confirmation dialog with useConfirm
Source: https://context7.com/jonatanklosko/material-ui-confirm/llms.txt
Simple confirmation dialog implementation with minimal options. Shows how to handle the confirmation promise and perform actions based on user response.
```jsx
import React from "react";
import Button from "@mui/material/Button";
import { useConfirm } from "material-ui-confirm";
function LogoutButton() {
const confirm = useConfirm();
const handleLogout = async () => {
const { confirmed } = await confirm({
description: "Are you sure you want to log out?",
});
if (confirmed) {
// Perform logout
localStorage.removeItem("authToken");
window.location.href = "/login";
}
};
return ;
}
export default LogoutButton;
```
--------------------------------
### React Confirmation Dialog Patterns
Source: https://context7.com/jonatanklosko/material-ui-confirm/llms.txt
Demonstrates three distinct confirmation patterns using material-ui-confirm library. First pattern forces user acknowledgment via checkbox before allowing confirmation. Second pattern prevents natural dialog closure by disabling escape key and backdrop clicks, requiring explicit user action. Third pattern replaces plain text with custom React elements for enhanced UI including icons, typography, and structured content.
```jsx
import React from "react";
import Button from "@mui/material/Button";
import { useConfirm } from "material-ui-confirm";
function DataExportButton() {
const confirm = useConfirm();
const handleExport = async () => {
const { confirmed } = await confirm({
title: "Export Sensitive Data",
description:
"You are about to export sensitive user data. This action will be logged and audited.",
acknowledgement: "I understand that this action is logged and audited",
confirmationText: "Export Data",
acknowledgementCheckboxProps: {
color: "warning",
},
confirmationButtonProps: {
color: "warning",
variant: "contained",
},
});
if (confirmed) {
const response = await fetch("/api/export/sensitive-data");
const blob = await response.blob();
const url = window.URL.createObjectURL(blob);
const a = document.createElement("a");
a.href = url;
a.download = "sensitive-data.csv";
a.click();
}
};
return (
);
}
export default DataExportButton;
```
```jsx
import React from "react";
import Button from "@mui/material/Button";
import { useConfirm } from "material-ui-confirm";
function CriticalOperationButton() {
const confirm = useConfirm();
const handleOperation = async () => {
const { confirmed, reason } = await confirm({
title: "Critical System Operation",
description:
"This operation will affect all users. You must explicitly confirm or cancel.",
allowClose: false,
confirmationText: "Proceed",
cancellationText: "Abort",
confirmationButtonProps: { color: "warning" },
dialogProps: {
disableEscapeKeyDown: true,
},
});
if (confirmed && reason === "confirm") {
await fetch("/api/critical-operation", { method: "POST" });
console.log("Operation executed");
} else {
console.log(`Operation aborted: ${reason}`);
}
};
return (
);
}
export default CriticalOperationButton;
```
```jsx
import React from "react";
import Button from "@mui/material/Button";
import Box from "@mui/material/Box";
import Typography from "@mui/material/Typography";
import WarningIcon from "@mui/icons-material/Warning";
import { useConfirm } from "material-ui-confirm";
function UpdateSystemButton() {
const confirm = useConfirm();
const handleUpdate = async () => {
const { confirmed } = await confirm({
title: "System Update Available",
content: (
Version 2.0.0
This update includes:
Breaking API changes
Database migrations
Estimated downtime: 15 minutes
Please backup your data before proceeding.
),
confirmationText: "Update Now",
cancellationText: "Later",
confirmationButtonProps: { color: "primary", variant: "contained" },
});
if (confirmed) {
await fetch("/api/system/update", { method: "POST" });
console.log("Update initiated");
}
};
return ;
}
export default UpdateSystemButton;
```
--------------------------------
### ConfirmProvider Component
Source: https://github.com/jonatanklosko/material-ui-confirm/blob/master/README.md
Wrapper component required to render confirmation dialogs in the component tree. Provides context for the confirmation dialogs.
```APIDOC
## ConfirmProvider
### Description
Wrapper component required to render confirmation dialogs in the component tree. Provides context for the confirmation dialogs.
### Method
Component
### Endpoint
N/A
### Parameters
#### Props
- **`defaultOptions`** (object) - Optional - Overrides the default options used by confirm function. Default: {}.
- **`useLegacyReturn`** (boolean) - Optional - 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. Default: false.
### Request Example
```jsx
{/* App content */}
```
### Response
#### Success Response
Returns a provider component that enables confirmation dialogs for its children.
```
--------------------------------
### Keyword confirmation for destructive actions
Source: https://context7.com/jonatanklosko/material-ui-confirm/llms.txt
Implementation of a confirmation dialog that requires users to type a specific keyword before confirming. Useful for high-risk operations like data deletion.
```jsx
import React from "react";
import Button from "@mui/material/Button";
import { useConfirm } from "material-ui-confirm";
function DeleteProjectButton({ projectName }) {
const confirm = useConfirm();
const handleDelete = async () => {
const { confirmed, reason } = await confirm({
title: `Delete Project: ${projectName}`,
description: `This will permanently delete the project and all its data. Type "${projectName}" to confirm.`,
confirmationText: "Delete Project",
cancellationText: "Cancel",
confirmationKeyword: projectName,
confirmationKeywordTextFieldProps: {
label: `Type "${projectName}" to confirm`,
placeholder: projectName,
variant: "outlined",
autoFocus: true,
},
confirmationButtonProps: { color: "error" },
});
if (confirmed) {
await fetch(`/api/projects/${projectName}`, { method: "DELETE" });
console.log("Project deleted");
}
};
return (
);
}
export default DeleteProjectButton;
```
--------------------------------
### Use useConfirm hook in React component (JavaScript)
Source: https://github.com/jonatanklosko/material-ui-confirm/blob/master/README.md
This code demonstrates using the useConfirm hook to create and handle a confirmation dialog. It requires the material-ui-confirm package and depends on the component being within ConfirmProvider. The hook takes an options object as input and returns a promise resolving to an object with 'confirmed' boolean and 'reason' string indicating user action. Limitations include requiring async/await or promise handling for the confirmation result.
```javascript
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 ;
};
export default Item;
```
--------------------------------
### Static Confirm Method (React/JavaScript)
Source: https://context7.com/jonatanklosko/material-ui-confirm/llms.txt
Shows how to use the confirm dialog without React hooks, useful for non-component contexts or class components. It leverages the `ConfirmProvider` and `confirm` function directly. Requires `material-ui-confirm`.
```jsx
import React from "react";
import Button from "@mui/material/Button";
import { ConfirmProvider, confirm } from "material-ui-confirm";
// Can be called from anywhere, even outside React components
async function performGlobalAction() {
const { confirmed } = await confirm({
title: "Global Action",
description: "This is called from outside a component",
});
if (confirmed) {
console.log("Action confirmed");
}
}
// Setup in App
function App() {
return (
);
}
// Usage in utility functions
export async function logoutUser() {
const { confirmed } = await confirm({
description: "Are you sure you want to log out?",
});
if (confirmed) {
localStorage.clear();
window.location.href = "/login";
}
}
export default App;
```
--------------------------------
### Use confirmation dialog with useConfirm hook
Source: https://context7.com/jonatanklosko/material-ui-confirm/llms.txt
The useConfirm hook returns a confirm function for displaying confirmation dialogs within functional components. It handles promise resolution with confirmation status and reason, and supports custom button props.
```jsx
import React from "react";
import Button from "@mui/material/Button";
import { useConfirm } from "material-ui-confirm";
function DeleteUserButton({ userId, onDeleted }) {
const confirm = useConfirm();
const handleDelete = async () => {
try {
const { confirmed, reason } = await confirm({
title: "Delete User",
description: "This action cannot be undone. Are you sure?",
confirmationText: "Delete",
cancellationText: "Cancel",
confirmationButtonProps: { color: "error", variant: "contained" },
});
if (confirmed && reason === "confirm") {
await fetch(`/api/users/${userId}`, { method: "DELETE" });
onDeleted(userId);
console.log("User deleted successfully");
} else {
console.log(`Dialog closed: ${reason}`);
}
} catch (error) {
console.error("Error during deletion:", error);
}
};
return (
);
}
export default DeleteUserButton;
```
--------------------------------
### Local confirmation dialog with autoFocus
Source: https://github.com/jonatanklosko/material-ui-confirm/blob/master/README.md
Demonstrates how to create a local confirmation dialog that auto-focuses the confirmation button, allowing confirmation by pressing Enter. Uses React and Material-UI.
```jsx
const MyComponent = () => {
// ...
const handleClick = async () => {
const { confirmed } = await confirm({
confirmationButtonProps: { autoFocus: true },
});
if (confirmed) {
/* ... */
}
};
// ...
};
```
--------------------------------
### Enable Legacy Return Mode with JSX in Material-UI Confirm
Source: https://context7.com/jonatanklosko/material-ui-confirm/llms.txt
This snippet demonstrates how to enable legacy promise behavior in material-ui-confirm for v3 compatibility, where the confirm function resolves on user confirmation and rejects on cancel. It requires React, Material-UI components, and the material-ui-confirm library. Outputs include promise resolution/rejection for handling confirm/cancel actions, with limitations in handling natural closes which keep the promise pending.
```jsx
import React from "react";
import { ConfirmProvider } from "material-ui-confirm";
import Button from "@mui/material/Button";
import { useConfirm } from "material-ui-confirm";
function App() {
return (
);
}
function LegacyComponent() {
const confirm = useConfirm();
const handleLegacyConfirm = () => {
confirm({ description: "Use legacy promise behavior?" })
.then(() => {
// Resolved on confirm
console.log("User confirmed");
})
.catch(() => {
// Rejected on cancel
console.log("User cancelled");
});
// Natural close keeps promise pending
};
return ;
}
export default App;
```
--------------------------------
### Global confirmation dialog configuration
Source: https://github.com/jonatanklosko/material-ui-confirm/blob/master/README.md
Shows how to set default options for all confirmation dialogs in an application, including auto-focusing the confirmation button. Uses React and Material-UI.
```jsx
const App = () => {
return (
{/* ... */}
);
};
```
--------------------------------
### confirm Function
Source: https://github.com/jonatanklosko/material-ui-confirm/blob/master/README.md
Function that opens a confirmation dialog and returns a promise representing the user choice. Resolves on confirmation and rejects on cancellation.
```APIDOC
## confirm
### Description
Function that opens a confirmation dialog and returns a promise representing the user choice. Resolves on confirmation and rejects on cancellation.
### Method
Function
### Endpoint
N/A
### Parameters
#### Options (object) - Optional
- Accepts various options for configuring the confirmation dialog
### Request Example
```js
const { confirmed, reason } = await confirm({
description: "This action is permanent!",
});
```
### Response
#### Success Response
- **`confirmed`** (boolean) - Whether the user confirmed the action
- **`reason`** (string) - The reason for closing: "confirm" | "cancel" | "natural" | "unmount"
#### Response Example
```js
{
"confirmed": true,
"reason": "confirm"
}
```
```
--------------------------------
### useConfirm Hook
Source: https://github.com/jonatanklosko/material-ui-confirm/blob/master/README.md
React hook that returns the confirm function for opening confirmation dialogs. Must be used within a ConfirmProvider.
```APIDOC
## useConfirm
### Description
React hook that returns the confirm function for opening confirmation dialogs. Must be used within a ConfirmProvider.
### Method
Hook
### Endpoint
N/A
### Parameters
No parameters
### Request Example
```jsx
const confirm = useConfirm();
const handleClick = async () => {
const { confirmed, reason } = await confirm({
description: "This action is permanent!",
});
// Handle result
};
```
### Response
#### Success Response
Returns the confirm function that can be used to open confirmation dialogs.
```
--------------------------------
### Reverse Confirm and Cancel Button Order (React/JSX)
Source: https://context7.com/jonatanklosko/material-ui-confirm/llms.txt
Demonstrates how to reverse the order of confirm and cancel buttons within the confirmation dialog. This uses the `buttonOrder` property to specify the desired button arrangement. It depends on `material-ui-confirm` and `@mui/material` libraries.
```jsx
import React from "react";
import Button from "@mui/material/Button";
import { useConfirm } from "material-ui-confirm";
function SaveChangesButton({ formData, onSaved }) {
const confirm = useConfirm();
const handleSave = async () => {
const { confirmed } = await confirm({
title: "Save Changes?",
description: "Do you want to save your changes before leaving?",
confirmationText: "Save",
cancellationText: "Discard",
buttonOrder: ["confirm", "cancel"],
confirmationButtonProps: { variant: "contained", color: "primary" },
cancellationButtonProps: { color: "error" },
});
if (confirmed) {
await fetch("/api/save", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(formData),
});
onSaved();
}
};
return ;
}
export default SaveChangesButton;
```
--------------------------------
### Hide Cancel Button (React/JSX)
Source: https://context7.com/jonatanklosko/material-ui-confirm/llms.txt
Shows only the confirm button in the dialog, helpful when no cancellation action is required. This utilizes the `hideCancelButton` property to hide the cancel button. It relies on `material-ui-confirm` and `@mui/material` libraries.
```jsx
import React from "react";
import Button from "@mui/material/Button";
import { useConfirm } from "material-ui-confirm";
function ShowTermsButton() {
const confirm = useConfirm();
const handleShowTerms = async () => {
await confirm({
title: "Terms of Service",
content: (
1. Acceptance of Terms...
2. User Responsibilities...
3. Privacy Policy...
{/* More terms content */}
),
confirmationText: "I Accept",
hideCancelButton: true,
confirmationButtonProps: { fullWidth: true, variant: "contained" },
});
// User must click accept to proceed
console.log("User accepted terms");
};
return ;
}
export default ShowTermsButton;
```
=== COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.