> Leaf UI 0.17.3 · Package: @ifhover/leaf-ui · Source: c3221834f84f2f48481a2054026b713456f8e5dc
> Browser documentation: https://ifhover.github.io/leaf-ui/en/components/modal.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.

# Modal

View or edit content in a dialog.

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


## Basic usage

[](#)
Associate the default confirm button with the form using `type="submit"` and a form ID to retain native validation. Update `open` in the form's `onSubmit` handler.


Edit title

basic.tsx

Copy code

```tsx lineNumbers file="../../../src/examples/en/modal/basic.tsx"
import { Button, Form, FormField, Input, Modal } from '@ifhover/leaf-ui';
import { useId, useState } from 'react';

export function ModalBasic() {
  const [open, setOpen] = useState(false);
  const formId = useId();
  return (
    <>
      <Button onClick={() => setOpen(true)}>Edit title</Button>
      <Modal
        open={open}
        title="Edit title"
        confirmText="Save"
        onClose={() => setOpen(false)}
        confirmButtonProps={{ type: 'submit', form: formId }}
      >
        <Form
          id={formId}
          layout="vertical"
          onSubmit={(event) => {
            event.preventDefault();
            setOpen(false);
          }}
        >
          <FormField label="Title" required>
            <Input name="title" defaultValue="Leaf UI" />
          </FormField>
        </Form>
      </Modal>
    </>
  );
}
```

Expand code


## Examples

### Icon and description

Use `icon` and `description` to add an icon and supporting description to the modal. Header and footer dividers are shown by default; set `divided={false}` to hide them.


Rename file

description.tsx

Copy code

```tsx lineNumbers file="../../../src/examples/en/modal/description.tsx"
import { Button, Form, FormField, Input, Modal } from '@ifhover/leaf-ui';
import { Pencil } from 'lucide-react';
import { useId, useState } from 'react';

export function ModalDescription() {
  const [open, setOpen] = useState(false);
  const formId = useId();
  return (
    <>
      <Button onClick={() => setOpen(true)}>Rename file</Button>
      <Modal
        open={open}
        title="Rename file"
        description="The new name will appear in the file list and downloads."
        icon={<Pencil />}
        confirmText="Save"
        onClose={() => setOpen(false)}
        confirmButtonProps={{ type: 'submit', form: formId }}
      >
        <Form
          id={formId}
          layout="vertical"
          onSubmit={(event) => {
            event.preventDefault();
            setOpen(false);
          }}
        >
          <FormField label="File name" required>
            <Input name="filename" defaultValue="Design notes.md" />
          </FormField>
        </Form>
      </Modal>
    </>
  );
}
```

Expand code

### Custom footer

A `footer` function receives the default buttons, so extra actions can retain their confirmation and cancellation behavior. Use `Space` to manage custom button spacing. Set `footer={null}` to hide the footer.


Custom footer

footer.tsx

Copy code

```tsx lineNumbers file="../../../src/examples/en/modal/footer.tsx"
import { Button, Modal, Paragraph, Space } from '@ifhover/leaf-ui';
import { useState } from 'react';

export function ModalFooter() {
  const [open, setOpen] = useState(false);
  const [details, setDetails] = useState(false);
  return (
    <>
      <Button onClick={() => setOpen(true)}>Custom footer</Button>
      <Modal
        open={open}
        title="About drafts"
        onClose={() => setOpen(false)}
        footer={({ cancelButton, confirmButton }) => (
          <Space size="sm" wrap>
            <Button variant="text" onClick={() => setDetails(!details)}>
              {details ? 'Hide details' : 'View details'}
            </Button>
            {cancelButton}
            {confirmButton}
          </Space>
        )}
      >
        <Paragraph>New documents are saved as drafts and can be edited later.</Paragraph>
        {details && <Paragraph>Drafts are visible only to you until you publish them.</Paragraph>}
      </Modal>
    </>
  );
}
```

Expand code

[](#)
### Destroy content on close

Content is preserved after the first opening by default. `destroyOnClose` unmounts it after the closing transition, so uncontrolled inputs return to their initial values when reopened. `preserve` takes precedence over `destroyOnClose`, while `forceRender` keeps content mounted. Controlled state held outside the dialog must still be reset by the application.


Open temporary draft

destroy.tsx

Copy code

```tsx lineNumbers file="../../../src/examples/en/modal/destroy.tsx"
import { Button, Form, FormField, Input, Modal } from '@ifhover/leaf-ui';
import { useId, useState } from 'react';

export function ModalDestroy() {
  const [open, setOpen] = useState(false);
  const formId = useId();
  return (
    <>
      <Button onClick={() => setOpen(true)}>Open temporary draft</Button>
      <Modal
        open={open}
        title="Temporary draft"
        destroyOnClose
        confirmText="Done"
        confirmButtonProps={{ type: 'submit', form: formId }}
        onClose={() => setOpen(false)}
      >
        <Form
          id={formId}
          layout="vertical"
          onSubmit={(event) => {
            event.preventDefault();
            setOpen(false);
          }}
        >
          <FormField label="Draft title">
            <Input name="draft" defaultValue="New draft" />
          </FormField>
        </Form>
      </Modal>
    </>
  );
}
```

Expand code

### Initial focus

Focus moves to the first focusable control by default. Use `initialFocus` to choose a different target. Closing restores the previously focused element; `returnFocus` can specify another destination.


Focus the input

focus.tsx

Copy code

```tsx lineNumbers file="../../../src/examples/en/modal/focus.tsx"
import { Button, FormField, Input, Modal } from '@ifhover/leaf-ui';
import { useRef, useState } from 'react';

export function ModalFocus() {
  const [open, setOpen] = useState(false);
  const inputRef = useRef<HTMLInputElement>(null);
  return (
    <>
      <Button onClick={() => setOpen(true)}>Focus the input</Button>
      <Modal open={open} title="Edit title" initialFocus={inputRef} onClose={() => setOpen(false)}>
        <FormField layout="vertical" label="Title">
          <Input ref={inputRef} defaultValue="Leaf UI" />
        </FormField>
      </Modal>
    </>
  );
}
```

Expand code

### Async submission

Return a Promise to show loading and prevent duplicate actions. Default cancellation, close-button, backdrop and Escape dismissal are blocked while it is pending. The application must still update `open` after `onConfirm` succeeds; rejection keeps the dialog open and displays the error.


Save title asynchronouslySaved: Leaf UI

async.tsx

Copy code

```tsx lineNumbers file="../../../src/examples/en/modal/async.tsx"
import { Button, FormField, Input, Modal, Space, Text } from '@ifhover/leaf-ui';
import { useState } from 'react';

export function ModalAsync() {
  const [open, setOpen] = useState(false);
  const [draft, setDraft] = useState('Leaf UI');
  const [saved, setSaved] = useState('Leaf UI');
  const [saving, setSaving] = useState(false);
  return (
    <Space direction="vertical" align="start">
      <Button
        onClick={() => {
          setDraft(saved);
          setOpen(true);
        }}
      >
        Save title asynchronously
      </Button>
      <Text tone="muted" role="status">
        Saved: {saved}
      </Text>
      <Modal
        open={open}
        title="Edit title"
        confirmText="Save"
        onClose={() => setOpen(false)}
        onConfirm={async () => {
          setSaving(true);
          try {
            await new Promise<void>((resolve) => setTimeout(resolve, 900));
            setSaved(draft);
            setOpen(false);
          } finally {
            setSaving(false);
          }
        }}
      >
        <FormField layout="vertical" label="Title">
          <Input
            value={draft}
            disabled={saving}
            onChange={(event) => setDraft(event.target.value)}
          />
        </FormField>
      </Modal>
    </Space>
  );
}
```

Expand code

### Tabbed modal

Use `tabs` to embed line tabs beneath the heading or in place of it when untitled. The tab bar stays fixed above the scrolling body and always keeps its bottom divider even when `divided={false}`. Omit item `children` when using the tabs solely to switch state for Modal's `children`.


Project settings

tabs.tsx

Copy code

```tsx lineNumbers file="../../../src/examples/en/modal/tabs.tsx"
import { Button, Modal, Text } from '@ifhover/leaf-ui';
import { useState } from 'react';

export function ModalTabs() {
  const [open, setOpen] = useState(false);
  return (
    <>
      <Button onClick={() => setOpen(true)}>Project settings</Button>
      <Modal
        open={open}
        title="Project settings"
        divided={false}
        onClose={() => setOpen(false)}
        tabs={{
          items: [
            {
              key: 'general',
              label: 'General',
              children: <Text>Display settings forms or details in separate tab panels.</Text>,
            },
            {
              key: 'members',
              label: 'Permissions',
              children: <Text>The tab bar stays fixed while only the body scrolls.</Text>,
            },
          ],
        }}
      />
    </>
  );
}
```

Expand code


## API

### Modal API

Control modal visibility, content and footer actions.

Provide `aria-label` when omitting `title`.

| Property             | Type                                                                                   | Default        | Description                                                                                                                                                                                                                                                                                                                                             |
| -------------------- | -------------------------------------------------------------------------------------- | -------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `open`               | `boolean`                                                                              | Required       | Controlled open state, updated by the application.                                                                                                                                                                                                                                                                                                      |
| `title`              | `ReactNode`                                                                            | —              | Dialog title.                                                                                                                                                                                                                                                                                                                                           |
| `description`        | `ReactNode`                                                                            | —              | Additional description.                                                                                                                                                                                                                                                                                                                                 |
| `tabs`               | [`ModalTabsProps`](#modaltabs-api)                                                     | —              | Embedded tabs; replace the heading when untitled or sit beneath it, retaining the tab bar bottom divider.                                                                                                                                                                                                                                               |
| `onClose`            | `() => void`                                                                           | —              | Requests closure; update open in the application                                                                                                                                                                                                                                                                                                        |
| `onConfirm`          | `() => void \| Promise<void>`                                                          | —              | Default confirm-button action, optionally returning a Promise; blocks repeated confirmation and built-in closing while pending. The application must still update open after success.                                                                                                                                                                   |
| `onCancel`           | `() => void`                                                                           | —              | Called when Cancel, the close button, the mask or Escape requests closing; falls back to onClose.                                                                                                                                                                                                                                                       |
| `confirmText`        | `ReactNode`                                                                            | Locale default | Content of the default confirm button, accepting text or a React node. `null` or `undefined` uses the current locale's `common.confirm` ("确定" in Simplified Chinese, "OK" in English). Applies to the default footer and `confirmButton` passed to a `footer` function; does not affect custom buttons.                                                 |
| `cancelText`         | `ReactNode`                                                                            | Locale default | Content of the default cancel button, accepting text or a React node. `null` or `undefined` uses the current locale's `common.cancel` ("取消" in Simplified Chinese, "Cancel" in English). Applies to the default footer and `cancelButton` passed to a `footer` function; does not affect custom buttons. Set `footer={null}` to hide the entire footer. |
| `confirmLoading`     | `boolean`                                                                              | `false`        | Confirm loading state                                                                                                                                                                                                                                                                                                                                   |
| `confirmButtonProps` | [`ButtonProps`](https://ifhover.github.io/leaf-ui/en/components/button.md#button-api)  | —              | Customize the default buttons                                                                                                                                                                                                                                                                                                                           |
| `cancelButtonProps`  | [`ButtonProps`](https://ifhover.github.io/leaf-ui/en/components/button.md#button-api)  | —              | Customize the default buttons                                                                                                                                                                                                                                                                                                                           |
| `footer`             | `ReactNode \| ((actions: `[`ModalFooterActions`](#modalfooteractions)`) => ReactNode)` | Cancel + OK    | Custom footer; null hides it; a function receives default buttons                                                                                                                                                                                                                                                                                       |
| `icon`               | `ReactNode`                                                                            | —              | Decorative icon to the left of the heading.                                                                                                                                                                                                                                                                                                             |
| `divided`            | `boolean`                                                                              | `true`         | Separate the heading, content and footer with subtle borders.                                                                                                                                                                                                                                                                                           |
| `width`              | `number \| string`                                                                     | `480`          | Width; numbers are pixels                                                                                                                                                                                                                                                                                                                               |
| `closable`           | `boolean`                                                                              | `true`         | Show the close button.                                                                                                                                                                                                                                                                                                                                  |
| `maskClosable`       | `boolean`                                                                              | `true`         | Request closing when the mask is clicked.                                                                                                                                                                                                                                                                                                               |
| `keyboard`           | `boolean`                                                                              | `true`         | Allow Escape to request closing.                                                                                                                                                                                                                                                                                                                        |
| `initialFocus`       | `RefObject<HTMLElement \| null> \| (() => HTMLElement \| null)`                        | —              | Specify initial focus; defaults to the first focusable element, which may be the close button.                                                                                                                                                                                                                                                          |
| `returnFocus`        | `boolean \| RefObject<HTMLElement \| null> \| (() => HTMLElement \| null)`             | —              | Restore focus on close; specify a destination or use false.                                                                                                                                                                                                                                                                                             |
| `afterClose`         | `() => void`                                                                           | —              | Called after the closing animation finishes                                                                                                                                                                                                                                                                                                             |
| `destroyOnClose`     | `boolean`                                                                              | `false`        | Unmount contents after closing; preserve takes precedence and forceRender keeps contents mounted.                                                                                                                                                                                                                                                       |
| `preserve`           | `boolean`                                                                              | —              | Control content preservation, taking precedence over destroyOnClose; does not reset external controlled state.                                                                                                                                                                                                                                          |
| `forceRender`        | `boolean`                                                                              | `false`        | Mount before opening and keep hidden while closed.                                                                                                                                                                                                                                                                                                      |
| `container`          | `Element \| DocumentFragment \| (() => Element \| DocumentFragment)`                   | —              | Portal mount target; may also return a ShadowRoot.                                                                                                                                                                                                                                                                                                      |

### ModalTabs API

See the [Tabs API
](tabs.html#tabs-api) (opens in a new tab) for embedded tab props. Modal fixes `type="line"`
 and `placement="top"`
, keeps the tab bar fixed above the scrollable body with its bottom divider always visible regardless of `divided={false}`
, and restores an ordinary modal when `items`
 is empty.
```ts
type ModalTabsProps = Omit<TabsProps, 'type' | 'placement' | 'children'>;
```

### ModalFooterActions

The default confirm and cancel buttons received by the footer render function.

| Property        | Type        | Default  | Description                               |
| --------------- | ----------- | -------- | ----------------------------------------- |
| `confirmButton` | `ReactNode` | Required | Default confirm button with loading state |
| `cancelButton`  | `ReactNode` | Required | Default cancel button                     |

### DialogFocusOptions

Configure focus handling when a dialog opens or closes.

| Property       | Type                                                                       | Default | Description                                                 |
| -------------- | -------------------------------------------------------------------------- | ------- | ----------------------------------------------------------- |
| `initialFocus` | `RefObject<HTMLElement \| null> \| (() => HTMLElement \| null)`            | —       | Specify initial focus after opening.                        |
| `returnFocus`  | `boolean \| RefObject<HTMLElement \| null> \| (() => HTMLElement \| null)` | —       | Restore focus on close; specify a destination or use false. |
