> Leaf UI 0.17.3 · Package: @ifhover/leaf-ui · Source: c3221834f84f2f48481a2054026b713456f8e5dc
> Browser documentation: https://ifhover.github.io/leaf-ui/en/components/confirm.html

> For AI agents: the complete documentation index is available at https://ifhover.github.io/leaf-ui/en/llms.txt, the full documentation bundle is available at https://ifhover.github.io/leaf-ui/en/llms-full.txt.

# Confirm

Ask for confirmation before an important action and await the user's choice.

Use [Modal](https://ifhover.github.io/leaf-ui/en/components/modal.md) for editing, or [Popconfirm](https://ifhover.github.io/leaf-ui/en/components/popconfirm.md) for a brief confirmation beside a trigger.

Set up [ConfigProvider](https://ifhover.github.io/leaf-ui/en/components/config-provider.md) at the application entry, then call `useConfirm()` in a child component. Each confirmation inherits the caller's theme and language.

```tsx
import { ConfigProvider } from '@ifhover/leaf-ui';

export function Root() {
  return (
    <ConfigProvider>
      <App />
    </ConfigProvider>
  );
}
```


## Basic usage

[](#)
`confirm()` returns `Promise<boolean>`: confirmation resolves to `true`, cancellation to `false`.


Save changes

simple.tsx

Copy code

```tsx lineNumbers file="../../../src/examples/en/confirm/simple.tsx"
import { Button, Space, Text, useConfirm } from '@ifhover/leaf-ui';
import { useState } from 'react';

export function ConfirmSimple() {
  const { confirm } = useConfirm();
  const [result, setResult] = useState('');
  return (
    <Space direction="vertical" align="start">
      <Button
        onClick={async () => {
          const accepted = await confirm({
            title: 'Save changes?',
            children: 'The new settings will take effect immediately.',
            confirmText: 'Save',
            cancelText: 'Keep editing',
          });
          setResult(accepted ? 'Changes saved' : 'Save cancelled');
        }}
      >
        Save changes
      </Button>
      {result && (
        <Text tone="muted" role="status">
          {result}
        </Text>
      )}
    </Space>
  );
}
```

Expand code


## Examples

### Semantic states

Use `type` to select a semantic state; it defaults to `info`. `type="default"` omits the built-in icon, and `icon={null}` hides the icon for any type. `success` hides Cancel by default; set `showCancel` to display it.


InformationSuccessWarning

status.tsx

Copy code

```tsx lineNumbers file="../../../src/examples/en/confirm/status.tsx"
import { Button, Space, useConfirm } from '@ifhover/leaf-ui';

export function ConfirmStatus() {
  const { confirm } = useConfirm();
  return (
    <Space wrap>
      <Button
        onClick={() =>
          confirm({
            type: 'info',
            title: 'Share this link?',
            children: 'Anyone with the link can view this page.',
          })
        }
      >
        Information
      </Button>
      <Button
        onClick={() =>
          confirm({
            type: 'success',
            title: 'Export ready',
            children: 'Your file is ready to download.',
          })
        }
      >
        Success
      </Button>
      <Button
        onClick={() =>
          confirm({
            type: 'warning',
            title: 'Leave this page?',
            children: 'Unsaved changes will be lost.',
          })
        }
      >
        Warning
      </Button>
    </Space>
  );
}
```

Expand code

### Async confirmation

[](#)
Place the async action in `onConfirm`. Success closes the dialog automatically and resolves to `true`. While pending, the default buttons show loading and prevent repeated confirmation or cancellation.


Delete project

basic.tsx

Copy code

```tsx lineNumbers file="../../../src/examples/en/confirm/basic.tsx"
import { Button, Space, Text, useConfirm } from '@ifhover/leaf-ui';
import { useState } from 'react';

export function ConfirmBasic() {
  const { confirm } = useConfirm();
  const [result, setResult] = useState('');
  return (
    <Space direction="vertical" align="start">
      <Button
        danger
        variant="outline"
        onClick={async () => {
          setResult('');
          const accepted = await confirm({
            title: 'Delete project',
            children: 'This cannot be undone. Continue?',
            type: 'danger',
            onConfirm: () => new Promise<void>((resolve) => setTimeout(resolve, 900)),
          });
          setResult(accepted ? 'Project deleted' : 'Deletion cancelled');
        }}
      >
        Delete project
      </Button>
      {result && (
        <Text tone="muted" role="status">
          {result}
        </Text>
      )}
    </Space>
  );
}
```

Expand code

### Failure and retry

A rejected `onConfirm` displays the error and keeps the dialog open for another attempt. Each new confirmation in this example fails once, then succeeds on the second attempt.


Submit with retry

retry.tsx

Copy code

```tsx lineNumbers file="../../../src/examples/en/confirm/retry.tsx"
import { Button, Space, Text, useConfirm } from '@ifhover/leaf-ui';
import { useState } from 'react';

export function ConfirmRetry() {
  const { confirm } = useConfirm();
  const [result, setResult] = useState('');
  return (
    <Space direction="vertical" align="start">
      <Button
        onClick={async () => {
          let attempts = 0;
          setResult('');
          const accepted = await confirm({
            type: 'warning',
            title: 'Submit changes?',
            children: 'The first attempt simulates a failure. Confirm again to retry.',
            onConfirm: async () => {
              await new Promise<void>((resolve) => setTimeout(resolve, 600));
              if (++attempts === 1) throw new Error('Unable to submit. Please try again.');
            },
          });
          setResult(accepted ? 'Changes submitted' : 'Submission cancelled');
        }}
      >
        Submit with retry
      </Button>
      {result && (
        <Text tone="muted" role="status">
          {result}
        </Text>
      )}
    </Space>
  );
}
```

Expand code


## API

### useConfirm API

The returned object is [`ConfirmApi`](#confirmapi). Requests in the same queue appear in sequence, after the previous dialog finishes closing. The Promise resolves when the decision closes the dialog, without waiting for its closing animation.

Unmounting the caller or provider resolves outstanding requests to `false`. It does not abort an async action already in progress or invoke `onCancel`.

| Prop      | Type                                                               | Default | Description                                                             |
| --------- | ------------------------------------------------------------------ | ------- | ----------------------------------------------------------------------- |
| `confirm` | [`(options: ConfirmOptions) => Promise<boolean>`](#confirmoptions) | —       | Resolves true on confirmation, false on cancellation or caller unmount. |

### ConfirmApi

The command interface returned by `useConfirm()`.

| Property  | Type                                                                   | Default  | Description                                                                                                                                               |
| --------- | ---------------------------------------------------------------------- | -------- | --------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `confirm` | `(options: `[`ConfirmOptions`](#confirmoptions)`) => Promise<boolean>` | Required | Resolve to a boolean on decision: true after successful confirmation, false on cancellation or caller unmount, without waiting for the closing animation. |

### ConfirmOptions

Content, actions and interaction settings supplied to `confirm()`.

| Property             | Type                                                                                  | Default                           | Description                                                                      |
| -------------------- | ------------------------------------------------------------------------------------- | --------------------------------- | -------------------------------------------------------------------------------- |
| `title`              | `ReactNode`                                                                           | —                                 | Confirmation heading.                                                            |
| `children`           | `ReactNode`                                                                           | —                                 | A short explanation of the action's consequences.                                |
| `onConfirm`          | `() => void \| Promise<void>`                                                         | —                                 | Close after success; keep the dialog open and show the error on rejection.       |
| `onCancel`           | `() => void`                                                                          | —                                 | Called on cancellation.                                                          |
| `type`               | `'default' \| 'danger' \| 'success' \| 'warning' \| 'info'`                           | `'info'`                          | Semantic icon and color; only danger changes the confirm button color.           |
| `icon`               | `ReactNode`                                                                           | —                                 | Semantic icon beside the title, or the explanation when untitled; null hides it. |
| `confirmText`        | `ReactNode`                                                                           | Locale default                    | Confirm button label.                                                            |
| `cancelText`         | `ReactNode`                                                                           | Locale default                    | Cancel button label.                                                             |
| `showCancel`         | `boolean`                                                                             | false for success; otherwise true | Show the cancel button.                                                          |
| `confirmButtonProps` | [`ButtonProps`](https://ifhover.github.io/leaf-ui/en/components/button.md#button-api) | —                                 | Confirm button props.                                                            |
| `cancelButtonProps`  | [`ButtonProps`](https://ifhover.github.io/leaf-ui/en/components/button.md#button-api) | —                                 | Cancel button props.                                                             |
| `width`              | `number \| string`                                                                    | `420`                             | Dialog width, in pixels for numbers.                                             |
| `closable`           | `boolean`                                                                             | `false`                           | Show a close button in the corner.                                               |
| `maskClosable`       | `boolean`                                                                             | `false`                           | Cancel when the backdrop is clicked.                                             |
| `keyboard`           | `boolean`                                                                             | `true`                            | Cancel when Escape is pressed.                                                   |
| `initialFocus`       | `RefObject<HTMLElement \| null> \| (() => HTMLElement \| null)`                       | —                                 | Initial focus target.                                                            |
| `returnFocus`        | `boolean \| RefObject<HTMLElement \| null> \| (() => HTMLElement \| null)`            | —                                 | Return focus after closing; set a target or disable with false.                  |
| `className`          | `string`                                                                              | —                                 | Dialog class name.                                                               |
| `style`              | `CSSProperties`                                                                       | —                                 | Dialog styles.                                                                   |

### ConfirmProvider API

Without `ConfigProvider`, wrap the application in `ConfirmProvider`. An explicit `ConfirmProvider` creates an independent queue; a nested `ConfigProvider` continues to share the existing queue.

```tsx
import { ConfirmProvider } from '@ifhover/leaf-ui';

export function Root() {
  return (
    <ConfirmProvider>
      <App />
    </ConfirmProvider>
  );
}
```

| Property   | Type        | Default | Description                                                                                                                        |
| ---------- | ----------- | ------- | ---------------------------------------------------------------------------------------------------------------------------------- |
| `children` | `ReactNode` | —       | Contents sharing this independent confirmation queue; ConfigProvider already supplies a queue and nested ConfigProviders reuse it. |
