JGuang

Modal

Modal · Ant Design

Preview
npm install antd@6.6.5 @ant-design/icons@6.3.4 dayjs@1.11.23

Modal

Display a modal dialog box, providing a title, content area, and action buttons.

When To Use

When requiring users to interact with the application, but without jumping to a new page and interrupting the user's workflow, you can use Modal to create a new floating layer over the current page to get user feedback or display information.

Additionally, if you need to show a simple confirmation dialog, you can use App.useApp hooks.

Examples

  • Basic · basic

  • Asynchronously close · async

  • Customized Footer · footer

  • mask · mask

  • Loading · loading

  • Customized Footer render function · footer-render

  • Use hooks to get context · hooks

  • Internationalization · locale

  • Manual to update destroy · manual

  • To customize the position of modal · position

  • Customize footer buttons props · button-props

  • Custom modal content render · modal-render

  • To customize the width of modal · width

  • Static Method · static-info

  • Static confirmation · confirm

  • destroy confirmation modal dialog · confirm-router

  • Custom semantic dom styling · style-class

API

Common props ref:Common props

PropertyDescriptionTypeDefaultVersionGlobal Config
afterCloseSpecify a function that will be called when modal is closed completelyfunction-×
cancelButtonPropsThe cancel button propsButtonProps-6.0.0
cancelTextText of the Cancel buttonReactNodeCancel×
centeredCentered Modalbooleanfalse5.24.0
classNamesCustomize class for each semantic structure inside the Modal component. Supports object or function.Record<SemanticDOM, string> | (info: { props }) => Record<SemanticDOM, string>-5.10.0
closableWhether a close (x) button is visible on top right or notboolean | ClosableTypetrue-5.16.0
closeIconCustom close icon. 5.7.0: close button will be hidden when setting to null or falseReactNode<CloseOutlined />5.14.0
confirmLoadingWhether to apply loading visual effect for OK button or notbooleanfalse×
destroyOnCloseWhether to unmount child components on onClosebooleanfalse×
destroyOnHiddenWhether to unmount child components on onClosebooleanfalse5.25.0×
focusTriggerAfterCloseWhether need to focus trigger element after dialog is closed. Please use focusable.focusTriggerAfterClose insteadbooleantrue4.9.0×
footerFooter content, set as footer={null} when you don't need default buttonsReactNode | (originNode: ReactNode, extra: { OkBtn: React.FC, CancelBtn: React.FC }) => ReactNode(OK and Cancel buttons)renderFunction: 5.9.0×
forceRenderForce render Modalbooleanfalse×
focusableConfiguration for focus management in the Modal{ trap?: boolean, focusTriggerAfterClose?: boolean }-6.2.06.4.0
getContainerThe mounted node for Modal but still display at fullscreenHTMLElement | () => HTMLElement | Selectors | falsedocument.body×
keyboardWhether support press esc to closebooleantrue×
maskMask effectboolean | {enabled?: boolean, blur?: boolean, closable?: boolean}truemask.closable: 6.3.06.0.0, mask.closable: 6.3.0
maskClosableWhether to close the modal dialog when the mask (area outside the modal) is clicked. Please use mask.closable instead.booleantrue-×
modalRenderCustom modal content render(node: ReactNode) => ReactNode-4.7.0×
okButtonPropsThe ok button propsButtonProps-6.0.0
okTextText of the OK buttonReactNodeOK×
okTypeButton type of the OK buttonstringprimary×
styleStyle of floating layer, typically used at least for adjusting the positionCSSProperties-5.7.0
stylesCustomize inline style for each semantic structure inside the Modal component. Supports object or function.Record<SemanticDOM, CSSProperties> | (info: { props })=> Record<SemanticDOM, CSSProperties>-5.10.0
loadingShow the skeletonboolean5.18.0×
scrollLockWhether to lock body scroll when modal opensbooleantrue6.5.0×
titleThe modal dialog's titleReactNode-×
openWhether the modal dialog is visible or notbooleanfalse×
widthWidth of the modal dialogstring | number | Breakpoint520Breakpoint: 5.23.0×
wrapClassNameThe class name of the container of the modal dialogstring-×
zIndexThe z-index of the Modalnumber1000×
onCancelSpecify a function that will be called when a user clicks mask, close button on top right or Cancel buttonfunction(e)-×
onOkSpecify a function that will be called when a user clicks the OK buttonfunction(e)-×
afterOpenChangeCallback when the animation ends when Modal is turned on and off(open: boolean) => void-5.4.0×

Note

  • The state of Modal will be preserved at it's component lifecycle by default, if you wish to open it with a brand new state every time, set destroyOnHidden on it.
  • There is a situation that using <Modal /> with Form, which won't clear fields value when closing Modal even you have set destroyOnHidden. You need <Form preserve={false} /> in this case.
  • Modal.method() RTL mode only supports hooks.

Modal.method()

There are five ways to display the information based on the content's nature:

  • Modal.info
  • Modal.success
  • Modal.error
  • Modal.warning
  • Modal.confirm

The items listed above are all functions, expecting a settings object as parameter. The properties of the object are follows:

PropertyDescriptionTypeDefaultVersion
afterCloseSpecify a function that will be called when modal is closed completelyfunction-4.9.0
autoFocusButtonSpecify which button to autofocus. Please use focusable.autoFocusButton insteadnull | ok | cancelok
cancelButtonPropsThe cancel button propsButtonProps-
cancelTextText of the Cancel button with Modal.confirmstringCancel
centeredCentered Modalbooleanfalse
classNameThe className of containerstring-
closableWhether a close (x) button is visible on top right of the confirm dialog or notboolean | ClosableTypefalse-
closeIconCustom close iconReactNodeundefined4.9.0
contentContentReactNode-
focusable.autoFocusButtonSpecify which button to autofocusnull | ok | cancelok6.2.0
footerFooter content, set as footer: null when you don't need default buttonsReactNode | (originNode: ReactNode, extra: { OkBtn: React.FC, CancelBtn: React.FC }) => ReactNode-renderFunction: 5.9.0
getContainerReturn the mount node for ModalHTMLElement | () => HTMLElement | Selectors | falsedocument.body
iconCustom iconReactNode<ExclamationCircleFilled />
keyboardWhether support press esc to closebooleantrue
maskMask effectboolean | {enabled?: boolean, blur?: boolean, closable?: boolean}true
maskClosableWhether to close the modal dialog when the mask (area outside the modal) is clicked. Please use mask.closable instead.booleanfalse-
scrollLockWhether to lock body scroll when modal opensbooleantrue6.5.0
okButtonPropsThe ok button propsButtonProps-
okTextText of the OK buttonstringOK
okTypeButton type of the OK buttonstringprimary
styleStyle of floating layer, typically used at least for adjusting the positionCSSProperties-
titleTitleReactNode-
widthWidth of the modal dialogstring | number416
wrapClassNameThe class name of the container of the modal dialogstring-4.18.0
zIndexThe z-index of the Modalnumber1000
onCancelClick to onCancel the callback, the parameter is the closing function, if it returns a promise, resolve means normal closing, reject means not closingfunction(close)-
onOkClick to onOk the callback, the parameter is the closing function, if it returns a promise, resolve means normal closing, reject means not closingfunction(close)-

All the Modal.methods will return a reference, and then we can update and close the modal dialog by the reference.

ClosableType

PropertyDescriptionTypeDefaultVersion
afterCloseSpecify a function that will be called when modal is closed completelyfunction--
closeIconCustom close iconReactNodeundefined-
disabledWhether disabled close iconbooleanfalse-
onCloseTrigger when modal closeFunctionundefined-
const modal = Modal.info();

modal.update({
  title: 'Updated title',
  content: 'Updated content',
});

// on 4.8.0 or above, you can pass a function to update modal
modal.update((prevConfig) => ({
  ...prevConfig,
  title: `${prevConfig.title} (New)`,
}));

modal.destroy();
  • Modal.destroyAll

Modal.destroyAll() could destroy all confirmation modal dialogs(Modal.confirm|success|info|error|warning). Usually, you can use it in router change event to destroy confirm modal dialog automatically without use modal reference to close( it's too complex to use for all modal dialogs)

import { browserHistory } from 'react-router';

// router change
browserHistory.listen(() => {
  Modal.destroyAll();
});

Modal.useModal()

When you need using Context, you can use contextHolder which created by Modal.useModal to insert into children. Modal created by hooks will get all the context where contextHolder are. Created modal has the same creating function with Modal.method.

const [modal, contextHolder] = Modal.useModal();

React.useEffect(() => {
  modal.confirm({
    // ...
  });
}, []);

return <div>{contextHolder}</div>;

modal.confirm return method:

  • destroy: Destroy current modal
  • update: Update current modal
  • then: (Hooks only) Promise chain call, support await operation
// Return `true` when click `onOk` and `false` when click `onCancel`
const confirmed = await modal.confirm({ ... });

Semantic DOM

Semantic nodeNative descriptionVersion
rootRoot element with relative positioning, top position, width, max-width, margins, bottom padding and other basic layout styles for modal container6.0.0
maskMask element with fixed positioning, z-index, background color, animation transitions and other mask layer styles5.13.0
containerModal container element with relative positioning, background, background-clip, border, border-radius, box-shadow, pointer-events, padding and other modal body styles6.0.0
wrapperWrapper element used for motion container with animation and transition effect styles5.13.0
headerHeader element with padding, bottom border and other header area styles5.13.0
titleTitle element with margin, color, font-weight, font-size, line-height, word-wrap and other title text styles6.0.0
bodyBody element with content area background color, padding and other content display styles5.13.0
footerFooter element with footer background color, padding, top border, border-radius and other footer area styles5.13.0
closePreview close button element, sets basic button styles6.4.0

Semantic description source: vendor/components/modal/demo/_semantic.tsx

Design Token

Types, inheritance and declarations retain the pinned native source. Defaults are computed by the native theme and may be overridden by ConfigProvider; this table does not invent static defaults.

TokenTypeNative description
headerBgstringBackground color of header
titleLineHeightnumber | stringLine height of title
titleFontSizenumber | stringFont size of title
titleColorstringFont color of title
contentBgstringBackground color of content
footerBgstringBackground color of footer
contentPaddingnumber | stringSee native declaration and inherited types
headerPaddingstring | numberSee native declaration and inherited types
headerBorderBottomstringSee native declaration and inherited types
headerMarginBottomnumberSee native declaration and inherited types
bodyPaddingnumberSee native declaration and inherited types
footerPaddingstring | numberSee native declaration and inherited types
footerBorderTopstringSee native declaration and inherited types
footerBorderRadiusstring | numberSee native declaration and inherited types
footerMarginTopstring | numberSee native declaration and inherited types
confirmBodyPaddingstring | numberSee native declaration and inherited types
confirmIconMarginInlineEndstring | numberSee native declaration and inherited types
confirmBtnsMarginTopstring | numberSee native declaration and inherited types

Declaration source: vendor/components/modal/style/index.ts

import type React from 'react';

import type { CSSObject } from '@ant-design/cssinjs';

import { unit } from '@ant-design/cssinjs';

import { getMediaSize } from '../../grid/style';

import { genFocusOutline, genFocusStyle, resetComponent } from '../../style';

import { initFadeMotion, initZoomMotion } from '../../style/motion';

import type {
  AliasToken,
  FullToken,
  GenerateStyle,
  GenStyleFn,
  GlobalToken,
  TokenWithCommonCls,
} from '../../theme/internal';

import { genStyleHooks, mergeToken } from '../../theme/internal';

/** Component only token. Which will handle additional calculation of alias token */
export interface ComponentToken {
  // Component token here
  /**
   * @desc 顶部背景色
   * @descEN Background color of header
   */
  headerBg: string;
  /**
   * @desc 标题行高
   * @descEN Line height of title
   */
  titleLineHeight: number | string;
  /**
   * @desc 标题字体大小
   * @descEN Font size of title
   */
  titleFontSize: number | string;
  /**
   * @desc 标题字体颜色
   * @descEN Font color of title
   */
  titleColor: string;
  /**
   * @desc 内容区域背景色
   * @descEN Background color of content
   */
  contentBg: string;
  /**
   * @desc 底部区域背景色
   * @descEN Background color of footer
   */
  footerBg: string;

  /** @internal */
  contentPadding: number | string;
  /** @internal */
  headerPadding: string | number;
  /** @internal */
  headerBorderBottom: string;
  /** @internal */
  headerMarginBottom: number;
  /** @internal */
  bodyPadding: number;
  /** @internal */
  footerPadding: string | number;
  /** @internal */
  footerBorderTop: string;
  /** @internal */
  footerBorderRadius: string | number;
  /** @internal */
  footerMarginTop: string | number;
  /** @internal */
  confirmBodyPadding: string | number;
  /** @internal */
  confirmIconMarginInlineEnd: string | number;
  /** @internal */
  confirmBtnsMarginTop: string | number;
}

/**
 * @desc Modal 组件的 Token
 * @descEN Token for Modal component
 */
export interface ModalToken extends FullToken<'Modal'> {
  /**
   * @desc 模态框头部高度
   * @descEN Height of modal header
   */
  modalHeaderHeight: number | string;
  /**
   * @desc 模态框底部边框颜色
   * @descEN Border color of modal footer
   */
  modalFooterBorderColorSplit: string;
  /**
   * @desc 模态框底部边框样式
   * @descEN Border style of modal footer
   */
  modalFooterBorderStyle: string;
  /**
   * @desc 模态框底部边框宽度
   * @descEN Border width of modal footer
   */
  modalFooterBorderWidth: number | string;
  /**
   * @desc 模态框关闭图标颜色
   * @descEN Color of modal close icon
   */
  modalCloseIconColor: string;
  /**
   * @desc 模态框关闭图标悬停颜色
   * @descEN Hover color of modal close icon
   */
  modalCloseIconHoverColor: string;
  /**
   * @desc 模态框关闭按钮尺寸
   * @descEN Size of modal close button
   */
  modalCloseBtnSize: number | string;
  /**
   * @desc 模态框确认图标尺寸
   * @descEN Size of modal confirm icon
   */
  modalConfirmIconSize: number | string;
  /**
   * @desc 模态框标题高度
   * @descEN Height of modal title
   */
  modalTitleHeight: number | string;
}

FAQ

Why content not update when Modal closed?

Modal will use memo to avoid content jumping when closed. Also, if you use Form in Modal, you can reset initialValues by calling resetFields in effect.

Why I can not access context, redux, ConfigProvider locale/prefixCls in Modal.xxx?

antd will dynamic create React instance by ReactDOM.render when call Modal methods. Whose context is different with origin code located context.

When you need context info (like ConfigProvider context), you can use Modal.useModal to get modal instance and contextHolder node. And put it in your children:

const [modal, contextHolder] = Modal.useModal();

// then call modal.confirm instead of Modal.confirm

return (
  <Context1.Provider value="Ant">
    {/* contextHolder is in Context1, which means modal will get context of Context1 */}
    {contextHolder}
    <Context2.Provider value="Design">
      {/* contextHolder is out of Context2, which means modal will not get context of Context2 */}
    </Context2.Provider>
  </Context1.Provider>
);

Note: You must insert contextHolder into your children with hooks. You can use origin method if you do not need context connection.

App Package Component can be used to simplify the problem of useModal and other methods that need to manually implant contextHolder.

How to set static methods prefixCls ?

You can config with ConfigProvider.config

Shared native props

Tips: The following generic properties apply to most antd components; those not supported are described separately.

PropertyDescriptionTypeDefault
styleThe additional styleCSSProperties-
classNameThe additional css classstring-
rootClassNameClassName on the root elementstring-
autoFocusAuto focus when component mounted, only effective for focusable elements like forms, links, etc.booleanfalse

Install and reproduce an example

npm install antd@6.6.5 @ant-design/icons@6.3.4 dayjs@1.11.23

Use ConfigProvider and native App; configure dayjs locale separately. Each example lists its complete source files and additional pinned dependencies in View code. Example names select demos, not universal component props. See the resource setup guide for theme, locale and SSR.

Native type references

The source viewer includes unchanged native implementations and the following source declarations. Inherited types remain in their native packages. English source comments are preserved as code reference.

  • vendor/components/modal/ConfirmDialog.tsx
  • vendor/components/modal/Modal.tsx
  • vendor/components/modal/PurePanel.tsx
  • vendor/components/modal/components/ConfirmCancelBtn.tsx
  • vendor/components/modal/components/ConfirmOkBtn.tsx
  • vendor/components/modal/components/NormalCancelBtn.tsx
  • vendor/components/modal/components/NormalOkBtn.tsx
  • vendor/components/modal/confirm.tsx
  • vendor/components/modal/context.ts
  • vendor/components/modal/index.tsx
  • vendor/components/modal/interface.ts
  • vendor/components/modal/shared.tsx
  • vendor/components/modal/style/index.ts
  • vendor/components/modal/useModal/HookModal.tsx
  • vendor/components/modal/useModal/index.tsx

Source and license

https://github.com/ant-design/ant-design/tree/4a39f54842eade4e565ab336ef6097cd7e723cdd

Original bilingual prose and executable examples are retained. Website-only embeds and token tables are expanded locally. Ant Design is MIT; separately listed dependency notices also apply. Upload previews block outbound requests and do not provide a backend.