JGuang

Modal

Modal · Material UI

Preview
npm install @mui/material@9.4.0 @emotion/react@11.14.0 @emotion/styled@11.14.1

Modal

Build a low-level modal surface with native focus and backdrop support.

This guide covers Material UI Core with the default Emotion engine; extensions and additional demos are explicitly classified.

Use case and business boundary

Prefer Dialog for a dialog experience; supply labels and an explicit exit, and do not disable focus safeguards casually.

Native composition and scope

Modal

Preserve native Material UI composition and types; do not substitute JGuang UI/Base UI/Radix APIs. Example entries are not extra components.

Native installation and initialization

npm install @mui/material@9.4.0 @emotion/react@11.14.0 @emotion/styled@11.14.1

Use native npm and Emotion, not an invented JGuang UI Registry URL. Place examples inside native ThemeProvider; choose CssBaseline or ScopedCssBaseline for the project. Inspect React, existing providers, lockfile and SSR first. Never overwrite files or conceal peer conflicts. This batch verified React 19.2.8; React 18 and below require matching react-is. See the included bilingual setup guide.

Practical native parameters

These selected parameters are not a flattened universal API. Preserve the native declaring owner, slot structure, nullable values and generics.

Owner.propPractical roleDeclaration source
Modal.openControlled native visibility; it does not fetch data or execute actions.Modal
Modal.onCloseNative request to close; reason/event signatures differ and the host updates open.Modal
Modal.keepMountedRetain hidden native children; their effects may still run.Modal
Modal.disableAutoFocusOpt out of Modal autofocus only with a verified alternative focus policy.Modal

Runnable native examples

Machine keys select example entries, not universal variant props. Native demo JSX/data stay unchanged; JGuang-authored acceptance fixtures are explicitly labelled.

  • Basic modal · BasicModal · upstream native demo
  • Nested modal · NestedModal · upstream native demo
  • Transitions · TransitionsModal · upstream native demo
  • Performance · KeepMountedModal · upstream native demo
  • Server-side modal · ServerModal · upstream native demo

Explicitly unsupported additional examples

These remain in the upstream inventory, not silently skipped or presented as working previews. Additional dependency/framework acceptance is required.

  • Transitions · SpringModal: @react-spring/web

Actual usage example

Unmodified pinned native demo; copy its required local helper files together.

import * as React from 'react';
import Box from '@mui/material/Box';
import Button from '@mui/material/Button';
import Typography from '@mui/material/Typography';
import Modal from '@mui/material/Modal';

const style = {
  position: 'absolute',
  top: '50%',
  left: '50%',
  transform: 'translate(-50%, -50%)',
  width: 400,
  bgcolor: 'background.paper',
  border: '2px solid #000',
  boxShadow: 24,
  p: 4,
};

export default function BasicModal() {
  const [open, setOpen] = React.useState(false);
  const handleOpen = () => setOpen(true);
  const handleClose = () => setOpen(false);

  return (
    <div>
      <Button onClick={handleOpen}>Open modal</Button>
      <Modal
        open={open}
        onClose={handleClose}
        aria-labelledby="modal-modal-title"
        aria-describedby="modal-modal-description"
      >
        <Box sx={style}>
          <Typography id="modal-modal-title" variant="h6" component="h2">
            Text in a modal
          </Typography>
          <Typography id="modal-modal-description" sx={{ mt: 2 }}>
            Duis mollis, est non commodo luctus, nisi erat porttitor ligula.
          </Typography>
        </Box>
      </Modal>
    </div>
  );
}

Example dependency boundaries

react, @mui/material/Box, @mui/material/Button, @mui/material/Typography, @mui/material/Modal, @mui/material/Backdrop, @mui/material/Fade

Direct Icons/System/Utils example imports require their matching 9.4.0 packages. Relative data/helpers are part of the example closure, not extra components. Remote images and simulated operations do not supply a backend.

Pinned upstream API metadata reference

These tables retain the upstream metadata, not a newly inferred generic type system. Conditional generics, inherited props and callback details are defined by the source declarations below. Theme defaults may override metadata defaults.

import Modal from '@mui/material/Modal';
import { Modal } from '@mui/material';
PropRequiredUpstream metadata type / constraintMetadata default
childrenyeselement—
openyesbool—
classesnoobject—
closeAfterTransitionnoboolfalse
componentnoelementType—
containernoHTML element | func—
disableAutoFocusnoboolfalse
disableEnforceFocusnoboolfalse
disablePortalnoboolfalse
disableRestoreFocusnoboolfalse
disableScrollLocknoboolfalse
hideBackdropnoboolfalse
keepMountednoboolfalse
onClosenofunc—
onTransitionEnternofunc—
onTransitionExitednofunc—
slotPropsno{ backdrop?: func | object, root?: func | object }{}
slotsno{ backdrop?: elementType, root?: elementType }{}
sxnoArray<func | object | bool> | func | object—

Native source declarations

Declarations/imports are extracted from pinned source without flattening unions or external inheritance. Original English comments/types are source reference, not a claim of translated upstream prose. Shared types stay in their native packages.

vendor/src/Modal/Modal.d.ts

import * as React from 'react';

import { SxProps } from '@mui/system';

import { OverrideProps } from '@mui/types';

import { SlotComponentProps } from '../utils/types';

import { PortalProps } from '../Portal';

import { Theme } from '../styles';

import Backdrop from '../Backdrop';

import { OverridableComponent } from '../OverridableComponent';

import { ModalClasses } from './modalClasses';

export interface ModalComponentsPropsOverrides {}

export interface ModalOwnerState extends ModalProps {
  exited: boolean;
}

export interface ModalSlots {
  /**
   * The component that renders the root.
   * @default 'div'
   */
  root?: React.ElementType | undefined;
  /**
   * The component that renders the backdrop.
   */
  backdrop?: React.ElementType | undefined;
}

export interface ModalOwnProps {
  /**
   * A single child content element.
   */
  children: React.ReactElement<unknown>;
  /**
   * Override or extend the styles applied to the component.
   */
  classes?: Partial<ModalClasses> | undefined;
  /**
   * @ignore
   */
  className?: string | undefined;
  /**
   * When set to true the Modal waits until a nested Transition is completed before closing.
   * @default false
   */
  closeAfterTransition?: boolean | undefined;
  /**
   * An HTML element or function that returns one.
   * The `container` will have the portal children appended to it.
   *
   * You can also provide a callback, which is called in a React layout effect.
   * This lets you set the container from a ref, and also makes server-side rendering possible.
   *
   * By default, it uses the body of the top-level document object,
   * so it's simply `document.body` most of the time.
   */
  container?: PortalProps['container'] | undefined;
  /**
   * If `true`, the modal will not automatically shift focus to itself when it opens, and
   * replace it to the last focused element when it closes.
   * This also works correctly with any modal children that have the `disableAutoFocus` prop.
   *
   * Generally this should never be set to `true` as it makes the modal less
   * accessible to assistive technologies, like screen readers.
   * @default false
   */
  disableAutoFocus?: boolean | undefined;
  /**
   * If `true`, the modal will not prevent focus from leaving the modal while open.
   *
   * Generally this should never be set to `true` as it makes the modal less
   * accessible to assistive technologies, like screen readers.
   * @default false
   */
  disableEnforceFocus?: boolean | undefined;
  /**
   * The `children` will be under the DOM hierarchy of the parent component.
   * @default false
   */
  disablePortal?: PortalProps['disablePortal'] | undefined;
  /**
   * If `true`, the modal will not restore focus to previously focused element once
   * modal is hidden or unmounted.
   * @default false
   */
  disableRestoreFocus?: boolean | undefined;
  /**
   * Disable the scroll lock behavior.
   * @default false
   */
  disableScrollLock?: boolean | undefined;
  /**
   * If `true`, the backdrop is not rendered.
   * @default false
   */
  hideBackdrop?: boolean | undefined;
  /**
   * Always keep the children in the DOM.
   * This prop can be useful in SEO situation or
   * when you want to maximize the responsiveness of the Modal.
   * @default false
   */
  keepMounted?: boolean | undefined;
  /**
   * Callback fired when the component requests to be closed.
   * The `reason` parameter can optionally be used to control the response to `onClose`.
   *
   * @param {object} event The event source of the callback.
   * @param {string} reason Can be: `"escapeKeyDown"`, `"backdropClick"`.
   */
  onClose?:
    | {
        bivarianceHack(event: {}, reason: 'backdropClick' | 'escapeKeyDown'): void;
      }['bivarianceHack']
    | undefined;
  /**
   * A function called when a transition enters.
   */
  onTransitionEnter?: (() => void) | undefined;
  /**
   * A function called when a transition has exited.
   */
  onTransitionExited?: (() => void) | undefined;
  /**
   * If `true`, the component is shown.
   */
  open: boolean;
  /**
   * The components used for each slot inside the Modal.
   * Either a string to use a HTML element or a component.
   * @default {}
   */
  slots?: ModalSlots | undefined;
  /**
   * The props used for each slot inside the Modal.
   * @default {}
   */
  slotProps?:
    | {
        root?:
          SlotComponentProps<'div', ModalComponentsPropsOverrides, ModalOwnerState> | undefined;
        backdrop?:
          | SlotComponentProps<typeof Backdrop, ModalComponentsPropsOverrides, ModalOwnerState>
          | undefined;
      }
    | undefined;
  /**
   * The system prop that allows defining system overrides as well as additional CSS styles.
   */
  sx?: SxProps<Theme> | undefined;
}

export interface ModalTypeMap<
  RootComponent extends React.ElementType = 'div',
  AdditionalProps = {},
> {
  props: AdditionalProps & ModalOwnProps;
  defaultComponent: RootComponent;
}

type ModalRootProps = NonNullable<ModalTypeMap['props']['slotProps']>['root'];

export declare const ModalRoot: React.FC<ModalRootProps>;

declare const Modal: OverridableComponent<ModalTypeMap>;

export type ModalProps<
  RootComponent extends React.ElementType = ModalTypeMap['defaultComponent'],
  AdditionalProps = {},
> = OverrideProps<ModalTypeMap<RootComponent, AdditionalProps>, RootComponent> & {
  component?: React.ElementType | undefined;
};

Post-install acceptance

Run strict types, production build and real interactions. Check keyboard labels/focus, disabled/error/read-only semantics where natively supported, both themes, narrow screens and reduced motion. Verify callbacks against the real host data; do not declare installation complete from copying a prompt. Initialization fixtures also require server HTML and warning-free hydration.

Source and license

https://github.com/mui/material-ui/tree/809a7717b4c050ba3f69b75300689f07c050a16e

MIT · @mui/material@9.4.0. Vendor originals and license are preserved. Full original upstream prose remains in vendor/docs and is not represented as fully translated.