Skip to main content
06

Accessible modal

Mediumreactportalsfocus managementa11y

Your code isn't saved yet: refreshing or leaving the page resets it. Saved progress comes with user accounts.

Build an accessible Modal dialog. App.js already opens it from the Delete account button and passes a title and some content. Right now Modal renders nothing. The CSS for .overlay, .dialog and .close is ready.

jsx
<Modal open={open} onClose={() => setOpen(false)} title="Delete your account?">
  ...
</Modal>

Requirements

  • While open is true, show the dialog centered over a dimmed overlay, with the title, a close (×) button and the children.
  • The dialog closes (by calling onClose) when the user:
    • presses Escape,
    • clicks the × button,
    • clicks the overlay outside the dialog. Clicks inside the dialog must not close it.
  • The page behind the dialog does not scroll while it is open.
  • Render the dialog at the end of document.body with a portal, so no parent's overflow or z-index can clip it.

Accessibility

  • The dialog has role="dialog", aria-modal="true" and aria-labelledby pointing to its title.
  • When it opens, focus moves into the dialog.
  • Focus is trapped: Tab and Shift+Tab cycle through the dialog's controls and never reach the page behind it.
  • When it closes, focus returns to the element that opened it.

Note

The preview updates as you type. There are no automated tests for this challenge yet: open and close the dialog in every way using only the keyboard, then compare with the reference solution.

Follow-ups interviewers ask

  • How would you build this with the native <dialog> element and showModal()? What do you get for free?
  • Nested dialogs: Escape should close only the top one.
  • Animate opening and closing, including keeping the dialog mounted until the closing animation ends.
  • Make the rest of the page inert while the dialog is open.

The approach

The component has no state of its own: open and onClose come from the parent. Everything else is side effects that exist only while the dialog is open, so they live in one useEffect that depends on open. Its cleanup undoes each of them, in one place:

On openOn close (cleanup)
Remember document.activeElementFocus it again
Focus the first control in the dialog
document.body.style.overflow = 'hidden'Restore the previous value
Add a keydown listener for Escape and TabRemove it

The portal

createPortal(..., document.body) renders the dialog at the end of <body>, while it stays a normal child in the React tree: context, state and events still flow through Modal's parent. Without the portal, a parent with overflow: hidden or its own stacking context could clip the dialog or put it behind other content.

Closing on the overlay

The handler checks event.target === event.currentTarget, so only clicks on the overlay itself count, not clicks that bubble up from inside the dialog. It uses onMouseDown rather than onClick: if a user starts selecting text in the input and releases the mouse over the overlay, click would fire on the overlay and close the dialog by accident.

The focus trap

On Tab, the handler collects the focusable elements in the dialog. If focus is on the last one, it moves to the first, and Shift+Tab on the first moves to the last. In between, the browser's normal Tab behaviour is left alone. The list is collected on each key press, so controls that appear or disappear inside the dialog are handled.

Loading diagram...

A stable onClose

The parent passes a new onClose arrow function on every render. If the effect depended on it, it would re-run on every parent render: focus would jump back to the first input while the user is typing. The solution keeps the latest onClose in a ref and depends only on open.

What interviewers look for

  • All four of: portal, focus management, Escape, and scroll lock, with cleanup for each.
  • Focus returning to the trigger on close. This is the step most candidates forget.
  • Knowing that native <dialog> with showModal() gives focus trapping, Escape and the top layer for free, and when you still need custom code.

Reference solution

src/Modal.js

jsx
import { useEffect, useId, useRef } from 'react'
import { createPortal } from 'react-dom'

const FOCUSABLE =
  'a[href], button:not([disabled]), input:not([disabled]), select:not([disabled]), ' +
  'textarea:not([disabled]), [tabindex]:not([tabindex="-1"])'

export default function Modal({ open, onClose, title, children }) {
  const dialogRef = useRef(null)
  const titleId = useId()
  // The latest onClose, so the effect below doesn't re-run when the parent re-renders.
  const onCloseRef = useRef(onClose)
  useEffect(() => {
    onCloseRef.current = onClose
  })

  useEffect(() => {
    if (!open) return
    const dialog = dialogRef.current
    const previouslyFocused = document.activeElement

    // Move focus into the dialog: the first focusable element, or the dialog itself.
    const first = dialog.querySelector(FOCUSABLE)
    ;(first ?? dialog).focus()

    // Stop the page behind from scrolling.
    const { overflow } = document.body.style
    document.body.style.overflow = 'hidden'

    function onKeyDown(event) {
      if (event.key === 'Escape') {
        event.stopPropagation()
        onCloseRef.current()
        return
      }
      if (event.key !== 'Tab') return
      // Trap focus: wrap from the last element to the first, and back.
      const elements = [...dialog.querySelectorAll(FOCUSABLE)]
      if (elements.length === 0) {
        event.preventDefault()
        return
      }
      const firstElement = elements[0]
      const lastElement = elements[elements.length - 1]
      if (event.shiftKey && document.activeElement === firstElement) {
        event.preventDefault()
        lastElement.focus()
      } else if (!event.shiftKey && document.activeElement === lastElement) {
        event.preventDefault()
        firstElement.focus()
      }
    }

    document.addEventListener('keydown', onKeyDown)
    return () => {
      document.removeEventListener('keydown', onKeyDown)
      document.body.style.overflow = overflow
      // Give focus back to whatever opened the dialog.
      previouslyFocused?.focus?.()
    }
  }, [open])

  if (!open) return null

  return createPortal(
    <div
      className="overlay"
      // Only a click that starts and ends on the overlay itself closes it.
      onMouseDown={(event) => {
        if (event.target === event.currentTarget) onClose()
      }}
    >
      <div
        ref={dialogRef}
        className="dialog"
        role="dialog"
        aria-modal="true"
        aria-labelledby={titleId}
        tabIndex={-1}
      >
        <h2 id={titleId}>{title}</h2>
        <button type="button" className="close" aria-label="Close" onClick={onClose}>
          ×
        </button>
        {children}
      </div>
    </div>,
    document.body,
  )
}