דילוג לתוכן הראשי
06

Modal נגיש

בינוניreactportalsfocus managementa11y

הקוד שלכם עדיין לא נשמר: רענון או יציאה מהדף מאפסים אותו. שמירת התקדמות תגיע יחד עם חשבונות משתמשים.

בנו דיאלוג Modal נגיש. App.js כבר פותח אותו מכפתור Delete account ומעביר title ותוכן. כרגע Modal לא מרנדר כלום. ה-CSS של .overlay, .dialog ו-.close מוכן.

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

דרישות

  • כל עוד open הוא true, מציגים את הדיאלוג במרכז מעל overlay כהה, עם ה-title, כפתור סגירה (×) וה-children.
  • הדיאלוג נסגר (על ידי קריאה ל-onClose) כשהמשתמש:
    • לוחץ Escape,
    • לוחץ על כפתור ה-×,
    • לוחץ על ה-overlay מחוץ לדיאלוג. לחיצות בתוך הדיאלוג לא סוגרות אותו.
  • הדף שמאחורי הדיאלוג לא נגלל כל עוד הוא פתוח.
  • מרנדרים את הדיאלוג בסוף document.body עם portal, כך שאף overflow או z-index של parent לא יכול לחתוך אותו.

נגישות

  • לדיאלוג יש role="dialog", aria-modal="true" ו-aria-labelledby שמצביע על הכותרת שלו.
  • כשהוא נפתח, ה-focus עובר לתוך הדיאלוג.
  • ה-focus לכוד: Tab ו-Shift+Tab עוברים במעגל בין הפקדים של הדיאלוג ואף פעם לא מגיעים לדף שמאחוריו.
  • כשהוא נסגר, ה-focus חוזר לאלמנט שפתח אותו.

הערה

ה-preview מתעדכן תוך כדי הקלדה. לאתגר הזה עוד אין בדיקות אוטומטיות: פתחו וסגרו את הדיאלוג בכל הדרכים רק עם המקלדת, ואז השוו לפתרון.

שאלות המשך שמראיינים שואלים

  • איך הייתם בונים את זה עם האלמנט הנייטיב <dialog> ו-showModal()? מה מקבלים בחינם?
  • דיאלוגים מקוננים: Escape צריך לסגור רק את העליון.
  • אנימציה של פתיחה וסגירה, כולל השארת הדיאלוג mounted עד שאנימציית הסגירה נגמרת.
  • להפוך את שאר הדף ל-inert כל עוד הדיאלוג פתוח.

הגישה

לקומפוננטה אין state משלה: open ו-onClose מגיעים מה-parent. כל השאר הם side effects שקיימים רק כל עוד הדיאלוג פתוח, ולכן הם חיים ב-useEffect אחד שתלוי ב-open. ה-cleanup שלו מבטל כל אחד מהם, במקום אחד:

בפתיחהבסגירה (cleanup)
זוכרים את document.activeElementמחזירים אליו focus
focus על הפקד הראשון בדיאלוג
document.body.style.overflow = 'hidden'מחזירים את הערך הקודם
מוסיפים listener של keydown ל-Escape ול-Tabמסירים אותו

ה-portal

createPortal(..., document.body) מרנדר את הדיאלוג בסוף ה-<body>, אבל ב-React tree הוא נשאר child רגיל: context, state ו-events עדיין עוברים דרך ה-parent של Modal. בלי ה-portal, parent עם overflow: hidden או stacking context משלו יכול לחתוך את הדיאלוג או לשים אותו מאחורי תוכן אחר.

סגירה בלחיצה על ה-overlay

ה-handler בודק event.target === event.currentTarget, כך שרק לחיצות על ה-overlay עצמו נחשבות, ולא לחיצות שעולות (bubbling) מתוך הדיאלוג. הוא משתמש ב-onMouseDown ולא ב-onClick: אם משתמש מתחיל לסמן טקסט ב-input ומשחרר את העכבר מעל ה-overlay, click היה נורה על ה-overlay וסוגר את הדיאלוג בטעות.

ה-focus trap

ב-Tab, ה-handler אוסף את האלמנטים ה-focusable בדיאלוג. אם ה-focus על האחרון, הוא עובר לראשון, ו-Shift+Tab על הראשון עובר לאחרון. באמצע, ההתנהגות הרגילה של Tab בדפדפן לא משתנה. הרשימה נאספת בכל לחיצה, כך שפקדים שמופיעים או נעלמים בתוך הדיאלוג מטופלים.

טוען דיאגרמה...

onClose יציב

ה-parent מעביר arrow function חדשה של onClose בכל render. אם ה-effect היה תלוי בה, הוא היה רץ מחדש בכל render של ה-parent: ה-focus היה קופץ חזרה ל-input הראשון בזמן שהמשתמש מקליד. הפתרון שומר את ה-onClose העדכני ב-ref ותלוי רק ב-open.

מה מראיינים מחפשים

  • כל הארבעה: portal, ניהול focus, Escape ו-scroll lock, עם cleanup לכל אחד.
  • החזרת ה-focus ל-trigger בסגירה. זה השלב שרוב המועמדים שוכחים.
  • לדעת ש-<dialog> נייטיב עם showModal() נותן focus trap, Escape ו-top layer בחינם, ומתי עדיין צריך קוד משלכם.

פתרון לדוגמה

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,
  )
}