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, and this page is available as Markdown at https://ifhover.github.io/leaf-ui/en/components/modal.md.

Modal

View or edit content in a dialog.

Use Confirm for a brief decision, or Popconfirm 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.

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>
    </>
  );
}

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.

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>
    </>
  );
}

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.

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>
    </>
  );
}

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.

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>
    </>
  );
}

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.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>
    </>
  );
}

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.

Saved: Leaf UI
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>
  );
}

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.

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>,
            },
          ],
        }}
      />
    </>
  );
}

API

Control modal visibility, content and footer actions.

Provide aria-label when omitting title.

PropertyTypeDefaultDescription
openbooleanRequiredControlled open state, updated by the application.
titleReactNode—Dialog title.
descriptionReactNode—Additional description.
tabsModalTabsProps—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.
confirmTextReactNodeLocale defaultContent 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.
cancelTextReactNodeLocale defaultContent 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.
confirmLoadingbooleanfalseConfirm loading state
confirmButtonPropsButtonProps—Customize the default buttons
cancelButtonPropsButtonProps—Customize the default buttons
footerReactNode | ((actions: ModalFooterActions) => ReactNode)Cancel + OKCustom footer; null hides it; a function receives default buttons
iconReactNode—Decorative icon to the left of the heading.
dividedbooleantrueSeparate the heading, content and footer with subtle borders.
widthnumber | string480Width; numbers are pixels
closablebooleantrueShow the close button.
maskClosablebooleantrueRequest closing when the mask is clicked.
keyboardbooleantrueAllow Escape to request closing.
initialFocusRefObject<HTMLElement | null> | (() => HTMLElement | null)—Specify initial focus; defaults to the first focusable element, which may be the close button.
returnFocusboolean | RefObject<HTMLElement | null> | (() => HTMLElement | null)—Restore focus on close; specify a destination or use false.
afterClose() => void—Called after the closing animation finishes
destroyOnClosebooleanfalseUnmount contents after closing; preserve takes precedence and forceRender keeps contents mounted.
preserveboolean—Control content preservation, taking precedence over destroyOnClose; does not reset external controlled state.
forceRenderbooleanfalseMount before opening and keep hidden while closed.
containerElement | DocumentFragment | (() => Element | DocumentFragment)—Portal mount target; may also return a ShadowRoot.

ModalTabs API

See the 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.

type ModalTabsProps = Omit<TabsProps, 'type' | 'placement' | 'children'>;

ModalFooterActions

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

PropertyTypeDefaultDescription
confirmButtonReactNodeRequiredDefault confirm button with loading state
cancelButtonReactNodeRequiredDefault cancel button

DialogFocusOptions

Configure focus handling when a dialog opens or closes.

PropertyTypeDefaultDescription
initialFocusRefObject<HTMLElement | null> | (() => HTMLElement | null)—Specify initial focus after opening.
returnFocusboolean | RefObject<HTMLElement | null> | (() => HTMLElement | null)—Restore focus on close; specify a destination or use false.