Back to Ant Design

Modal

components/modal/index.en-US.md

6.3.712.4 KB
Original Source

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

<!-- prettier-ignore -->

<code src="./demo/basic.tsx">Basic</code> <code src="./demo/async.tsx">Asynchronously close</code> <code src="./demo/footer.tsx">Customized Footer</code> <code src="./demo/mask.tsx">mask</code> <code src="./demo/loading.tsx" version="5.18.0">Loading</code> <code src="./demo/footer-render.tsx" version="5.9.0">Customized Footer render function</code> <code src="./demo/hooks.tsx">Use hooks to get context</code> <code src="./demo/locale.tsx">Internationalization</code> <code src="./demo/manual.tsx">Manual to update destroy</code> <code src="./demo/position.tsx">To customize the position of modal</code> <code src="./demo/dark.tsx" debug>Demo for debugging</code> <code src="./demo/button-props.tsx">Customize footer buttons props</code> <code src="./demo/modal-render.tsx">Custom modal content render</code> <code src="./demo/width.tsx">To customize the width of modal</code> <code src="./demo/static-info.tsx">Static Method</code> <code src="./demo/confirm.tsx">Static confirmation</code> <code src="./demo/confirm-router.tsx">destroy confirmation modal dialog</code> <code src="./demo/style-class.tsx" version="6.0.0">Custom semantic dom styling</code> <code src="./demo/nested.tsx" debug>Nested Modal</code> <code src="./demo/render-panel.tsx" debug>_InternalPanelDoNotUseOrYouWillBeFired</code> <code src="./demo/custom-mouse-position.tsx" debug>Control modal's animation origin position</code> <code src="./demo/wireframe.tsx" debug>Wireframe</code> <code src="./demo/component-token.tsx" debug>Component Token</code>

API

Common props ref:Common props

PropertyDescriptionTypeDefaultVersion
afterCloseSpecify a function that will be called when modal is closed completelyfunction-
cancelButtonPropsThe cancel button propsButtonProps-
cancelTextText of the Cancel buttonReactNodeCancel
centeredCentered Modalbooleanfalse
classNamesCustomize class for each semantic structure inside the Modal component. Supports object or function.Record<SemanticDOM, string> | (info: { props }) => Record<SemanticDOM, string>-
closableWhether a close (x) button is visible on top right or notboolean | ClosableTypetrue-
closeIconCustom close icon. 5.7.0: close button will be hidden when setting to null or falseReactNode<CloseOutlined />
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.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.0
maskClosableWhether to close the modal dialog when the mask (area outside the modal) is clickedbooleantrue
modalRenderCustom modal content render(node: ReactNode) => ReactNode-4.7.0
okButtonPropsThe ok button propsButtonProps-
okTextText of the OK buttonReactNodeOK
okTypeButton type of the OK buttonstringprimary
styleStyle of floating layer, typically used at least for adjusting the positionCSSProperties-
stylesCustomize inline style for each semantic structure inside the Modal component. Supports object or function.Record<SemanticDOM, CSSProperties> | (info: { props })=> Record<SemanticDOM, CSSProperties>-
loadingShow the skeletonboolean5.18.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.

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}true
maskClosableWhether to close the modal dialog when the mask (area outside the modal) is clickedbooleanfalse
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-
jsx
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)

jsx
import { browserHistory } from 'react-router';

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

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.

jsx
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
tsx
// Return `true` when click `onOk` and `false` when click `onCancel`
const confirmed = await modal.confirm({ ... });

Semantic DOM

<code src="./demo/_semantic.tsx" simplify="true"></code>

Design Token

<ComponentTokenTable component="Modal"></ComponentTokenTable>

FAQ

Why content not update when Modal closed? {#faq-content-not-update}

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? {#faq-context-redux}

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:

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

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

return (
  <Context1.Provider value="Ant">
    {contextHolder}
    <Context2.Provider value="Design">
    </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 ? {#faq-set-prefix-cls}

You can config with ConfigProvider.config