Import
import { Modal } from '@contentful/f36-components';// orimport { Modal } from '@contentful/f36-modal';
⚠️ Deprecated props:
title,subtitleandmodalHeaderPropsonModal,onCloseonModal.Header, andheaderPropsonBasicModal(usemodalHeaderProps), are deprecated and will be removed in the next major version (v7). Use theheaderandcontrolsslots instead. See the migration guide.
Content and slots
Everything you pass as children is rendered inside the Modal.Content compound component, which provides the padding and scrolling of the modal body. Use modalContentProps to customize this wrapper.
This is the main reason to use the header and controls slots: header (takes Modal.Header or Modal.DisplayHeader) is rendered above the Modal.Content wrapper, and controls (takes Modal.Controls) is rendered underneath it. Passing a header or buttons as children would put them inside the scrollable content area instead.
<ModalisShown={isShown}onClose={onClose}header={<Modal.Header title="Create content type" />}controls={<Modal.Controls>{/* buttons */}</Modal.Controls>}>{/* rendered inside Modal.Content */}</Modal>
Rendering children without a wrapper
To render children without the Modal.Content wrapper, pass a function as children. The header and controls slots are still rendered around its result, but modalContentProps and the default header are not applied. Use this sparingly, only when you need full control over the layout of the modal body.
<ModalisShown={isShown}onClose={onClose}header={<Modal.Header title="Custom layout" />}>{() => <CustomFullBleedLayout />}</Modal>
Examples
Use Modal:
- to request information critical for a user to continue their current process
- to warn users about a potentially destructive action they are taking
Don't use Modal:
- for nonessential information that is not related to the current user flow
- for interrupting high-stake processes such as checkout flows
General usage
The close button in Modal.Header is wired to the modal's onClose automatically.
To keep users from closing the modal while an async action is pending, set shouldDisableCloseButton (and shouldCloseOnEscapePress/shouldCloseOnOverlayClick to false) instead of removing onClose.
function ModalGeneralUsageExample() { const [isShown, setShown] = useState(false); return ( <> <Button onClick={() => setShown(true)}>Open modal</Button> <Modal isShown={isShown} onClose={() => setShown(false)} header={<Modal.Header title="Modal title" subtitle="subtitle" />} > <Heading> First entry published! It can now be fetched via the APIs </Heading> <Paragraph> To discover more about how to consume content from the APIs, go to Space Home. </Paragraph> </Modal> </> ); }
Modal with Form
function ModalWithFormExample() { const [isShown, setShown] = useState(false); const [contentTypeName, setContentTypeName] = useState(''); const submitForm = () => { if (contentTypeName.length === 0) { return; } alert('Created: ' + contentTypeName); setContentTypeName(''); setShown(false); }; return ( <> <Button onClick={() => setShown(true)}>Create new content type</Button> <Modal isShown={isShown} onClose={() => setShown(false)} header={<Modal.Header title="Create new content type" />} controls={ <Modal.Controls> <Button size="small" variant="transparent" onClick={() => setShown(false)} > Close </Button> <Button size="small" variant="positive" isDisabled={contentTypeName.length === 0} onClick={submitForm} > Create </Button> </Modal.Controls> } > <Form onSubmit={submitForm}> <FormControl> <FormControl.Label isRequired>Name</FormControl.Label> <TextInput maxLength={20} value={contentTypeName} placeholder="For example Product, Blog Post, Author" onChange={(e) => { setContentTypeName(e.target.value); }} /> </FormControl> </Form> </Modal> </> ); }
Modal with child component in Header
function ModalWithChildComponentInHeaderExample() { const [isShown, setShown] = useState(false); return ( <> <Button onClick={() => setShown(true)}>Open modal</Button> <Modal isShown={isShown} onClose={() => setShown(false)} header={ <Modal.Header title="With Child Component"> <Badge>Child Component</Badge> </Modal.Header> } > Modal content </Modal> </> ); }
Custom title and subtitle ids
The title and subtitle receive generated ids, which Modal uses for aria-labelledby and aria-describedby. If you need stable ids, pass titleId and subtitleId to Modal.Header. The ids are read on mount only.
function ModalWithCustomIdsExample() { const [isShown, setShown] = useState(false); return ( <> <Button onClick={() => setShown(true)}>Open modal</Button> <Modal isShown={isShown} onClose={() => setShown(false)} header={ <Modal.Header title="Modal title with custom id" subtitle="Subtitle with custom id" titleId="my-modal-title" subtitleId="my-modal-subtitle" /> } > Modal content </Modal> </> ); }
BasicModal
BasicModal is a shortcut for a modal with a title. Pass title and subtitle directly; use modalHeaderProps for any other Modal.Header props.
function BasicModalComponentExample() { const [isShown, setShown] = useState(false); return ( <> <Button onClick={() => setShown(true)}>Add to release</Button> <BasicModal title="Add to release" subtitle="Spring campaign" isShown={isShown} onClose={() => setShown(false)} controls={ <Modal.Controls> <Button size="small" variant="secondary" onClick={() => setShown(false)} > Cancel </Button> <Button size="small" variant="primary" onClick={() => setShown(false)} > Add to release </Button> </Modal.Controls> } > <Text>This entry will be published together with the release.</Text> </BasicModal> </> ); }
DisplayModal
DisplayModal shows a centered header with an optional illustration, and centered controls. Use it for onboarding or informative moments, not for forms.
function ModalDisplayExample() { const [isShown, setShown] = useState(false); return ( <> <Button onClick={() => setShown(true)}>Show display modal</Button> <DisplayModal illustration={ <CheckCircleIcon color={tokens.green500} style={{ width: 64, height: 64 }} /> } title="Set up your first content type" subtitle="It only takes a minute" isShown={isShown} onClose={() => setShown(false)} controls={ <Button variant="primary" onClick={() => setShown(false)}> Create content type </Button> } > <Text> Content types define the structure of your entries, such as a blog post or a product. </Text> </DisplayModal> </> ); }
Changing sizes
There are 4 different sizes for modals: small, medium, large, fullWidth, and fullscreen. Pick a size based on the amount of content you have to present in them.
You can also pass an arbitary width in pixels, but we recommend to choose of the predefined values.
function ModalSizesExample() { const [isShown, setShown] = useState(false); const [size, setSize] = useState('medium'); return ( <> <Form> <FormControl> <FormControl.Label>Select a width</FormControl.Label> <Select onChange={(e) => { setSize(e.target.value); }} value={size} > <Select.Option value="small">small</Select.Option> <Select.Option value="medium">medium</Select.Option> <Select.Option value="large">large</Select.Option> <Select.Option value="fullWidth">full width</Select.Option> <Select.Option value="fullscreen">full screen</Select.Option> <Select.Option value="333px"> 333px (specific width value) </Select.Option> </Select> </FormControl> <Button onClick={() => { setShown(true); }} > Click to open a modal </Button> </Form> <Modal isShown={isShown} onClose={() => setShown(false)} size={size} header={<Modal.Header title="A modal with a specific size" />} controls={ <Modal.Controls> <Button variant="transparent" size="small" onClick={() => setShown(false)} > Close </Button> <Button variant="positive" size="small" onClick={() => setShown(false)} > Confirm </Button> </Modal.Controls> } > <Text> My size is <strong>{size}</strong> </Text> </Modal> </> ); }
Choosing a fullWidth modal
As a rule of thumb, fullWidth modals shouldn’t be used frequently. Use them modals specially to present imagery or when you need to present a layout with columns in it. Never use fullWidth modals for a single column layout as the length of the line will affect readability.
Setting initial focus
When the modal opens, focus is automatically set to the close button, but you have the possibility to set an initial focus to a specific element of your modal dialog.
Either by using the initialFocusRef prop:
function ModalInitialFocusRefExample() { const [isShown, setShown] = useState(false); const inputRef = useRef(null); return ( <> <Button onClick={() => setShown(true)}>Create new content type</Button> <Modal isShown={isShown} onClose={() => setShown(false)} initialFocusRef={inputRef} header={<Modal.Header title="Create new content type" />} > <FormControl> <FormControl.Label isRequired>Name</FormControl.Label> <TextInput ref={inputRef} maxLength={20} placeholder="For example Product, Blog Post, Author" /> </FormControl> </Modal> </> ); }
... or by setting the autoFocus attribute to an interactive element, such as an input or button:
function ModalAutoFocusExample() { const [isShown, setShown] = useState(false); return ( <> <Button onClick={() => setShown(true)}>Create new content type</Button> <Modal isShown={isShown} onClose={() => setShown(false)} header={<Modal.Header title="Create new content type" />} > <FormControl> <FormControl.Label isRequired>Name</FormControl.Label> <TextInput autoFocus maxLength={20} placeholder="For example Product, Blog Post, Author" /> </FormControl> </Modal> </> ); }
Using Modal.Controls
Using Modal.Controls is optional and you may have a modal without control buttons. When you have control buttons, follow the following rules:
- always use
Buttoncomponent withsize="small" - your primary action button should be aligned to the right
- there should be only one primary action
- ideally, 1 secondary button should be enough when paired with a primary one. It’s allowed, however, to add a second one for another action.
Using ModalLauncher
When you want to open a modal from a function (outside of React component code), use ModalLauncher.
Props (API reference)
Open in StorybookName | Type | Default |
|---|---|---|
| children required | ReactNode | RenderModal | |
| isShown required | false true When true, the dialog is shown. | |
| onClose required | (event: MouseEvent<Element, MouseEvent> | KeyboardEvent<Element>) => void Function that will be run when the modal is requested to be closed, prior to actually closing. | |
| allowHeightOverflow | false true Are modals higher than viewport allowed | false |
| aria | Aria & { label?: string; } Additional aria attributes | |
| className | string CSS class to be appended to the root element | |
| closeIconLabel | string Accessible label of the header close button. `aria.closeIconLabel` on `Modal.Header` takes precedence. | Close |
| controls | ReactElement<ModalControlsProps, { ({ testId, className, children, justifyContent, ...otherProps }: ModalControlsProps): ReactElement<unknown, string | JSXElementConstructor<any>>; displayName: string; }> Controls slot, takes a `<Modal.Controls />`. Rendered below the content. | |
| header | ReactElement<ModalHeaderProps, { (props: ModalHeaderProps): ReactElement<unknown, string | JSXElementConstructor<any>>; displayName: string; }> ReactElement<ModalDisplayHeaderProps, { ({ title, titleId, subtitleId, subtitle, testId, className, illustration, aria, ...otherProps }: ModalDisplayHeaderProps): ReactElement<unknown, string | JSXElementConstructor<any>>; displayName: string; }> Header slot, takes a `<Modal.Header />` or `<Modal.DisplayHeader />`. Rendered above the content. The header shows a close button wired to `onClose` while the modal is dismissable. Wins over `title`/`subtitle` if both are set. | |
| initialFocusRef | RefObject<HTMLElement> Optional property to set initial focus | |
| modalContentProps | Partial<ModalContentProps> Optional props to override ModalContent behaviour | |
| modalHeaderProps Deprecated | Partial<ModalHeaderProps> Optional props to override ModalHeader behaviour | |
| onAfterOpen | OnAfterOpenCallback Function that will be run after the modal has opened. | |
| overlayProps | Pick<CommonProps, "className" | "style"> Optional props to override overlay behaviour | |
| position | "center" "top" Indicating if modal is centered or linked to the top | center |
| shouldCloseOnEscapePress | false true Boolean indicating if pressing the esc key should close the overlay. | true |
| shouldCloseOnOverlayClick | false true Boolean indicating if clicking the overlay should close the overlay. | true |
| shouldDisableCloseButton | false true Disables the header close button | false |
| size | string number Size of the modal window | medium |
| subtitle Deprecated | string Modal subtitle that is used in header | |
| testId | string A [data-test-id] attribute used for testing purposes | cf-ui-modal |
| title Deprecated | string Modal title that is used in header | |
| topOffset | string number Top offset if position is 'top' | 50px |
Content guidelines
For general guidelines around content and how to better write copy, consult this UX writing page . Find below a few suggestions on how to elaborate good content for modals:
Titles
Make them brief and easily inteligible, following this structure: verb + noun
âś… Do:
- Create content type
- Delete entry?
- Add to release
❌ Don't:
- Do you want to add this page to your release?
- Permanently delete this entry?
- Are you sure you want to delete this entry?
Body
The body is the main content of a modal. Therefore, try not to get chatty and keep it to the information that is necessary for users to accomplish their tasks. For more guidance on how to write good content for a modal, refer to this UX writing document.
Buttons label
A good way to think about buttons labels is to mentalize what users will be thinking when pressing the button. Actions should be clear and have a verb + noun structure that describes the action.
Buttons in modals should be short and sweet and shouldn’t require a lot of effort from users to understand what’s going to happen.
As a rule of thumb, users shouldn’t feel unclear of the outcomes of clicking on a specific button.
âś… Do: Add field, Remove page, Create content type, Add page to release
❌ Don't: Discard, New page, New content type, Go, Add
Avoid vague actions such as Remove (without saying what’s going to be removed) or Add.
Another scenario to avoid is to create lengthy buttons and with more that one action being described.
Accessibility
- When the modal opens, focus is trapped within it.
- When the modal opens, focus is automatically set to the close button, or the element from
initialFocusRef. - When the modal closes, focus returns to the element that was focused before the modal activated.
- By default, clicking on the overlay closes the modal.
- By default, pressing
Esccloses the modal. - Scrolling is blocked on the elements behind the modal.
- The modal's accessible name is linked automatically to the
title(aria-labelledby), and its description to thesubtitle(aria-describedby). Passingaria.labelledbyoraria.labeltakes precedence and turns off the automatic title and subtitle linking. Passingaria.describedbytakes precedence over the subtitle link.