새로운 도구가 추가되었습니다! 새로운 소식 보기

홈/컴포넌트/모달 다이얼로그

모달 다이얼로그 examples

백드롭, 포커스 트랩, Esc 키로 닫기 기능을 갖춘 네이티브 dialog 엘리먼트 기반의 접근성 모달입니다.

브라우저의 네이티브 dialog 엘리먼트로 구축된 모달 다이얼로그로, 포커스 트랩, 백드롭 렌더링, Esc 키로 닫기 기능이 직접 유지보수해야 하는 자바스크립트가 아니라 플랫폼에서 제공됩니다.

백드롭 클릭으로 닫기, 올바른 ARIA 레이블링, 그리고 open prop을 엘리먼트의 자체 메서드와 동기화하는 React 래퍼가 포함되어 있습니다.

Confirmation modal dialog

Two actions with the destructive one in red and placed last. The button names the action, so it reads correctly on its own.

Preview
"use client";

import { useRef } from "react";

export default function ConfirmDialog() {
  const ref = useRef<HTMLDialogElement>(null);

  return (
    <>
      <button
        type="button"
        onClick={() => ref.current?.showModal()}
        className="rounded-md bg-gray-900 px-4 py-2 text-sm font-medium text-white hover:bg-gray-700"
      >
        Delete project
      </button>

      <dialog
        ref={ref}
        onClick={(e) => {
          if (e.target === ref.current) ref.current?.close();
        }}
        aria-labelledby="dialog-title"
        aria-describedby="dialog-description"
        className="m-auto w-full max-w-md rounded-xl p-0 backdrop:bg-gray-900/50"
      >
        <div className="p-6">
          <h2 id="dialog-title" className="text-lg font-semibold text-gray-900">Delete this project?</h2>
          <p id="dialog-description" className="mt-2 text-sm text-gray-600">
            This removes the project and all of its files. This action cannot be undone.
          </p>

          <div className="mt-6 flex justify-end gap-3">
            <button type="button" onClick={() => ref.current?.close()} className="rounded-md border border-gray-300 px-4 py-2 text-sm font-medium text-gray-900 hover:bg-gray-50">Cancel</button>
            <button type="button" onClick={() => ref.current?.close()} className="rounded-md bg-red-600 px-4 py-2 text-sm font-medium text-white hover:bg-red-500">Delete project</button>
          </div>
        </div>
      </dialog>
    </>
  );
}

Modal dialog with a form

A single-field form using method=dialog, so submitting closes the dialog and reports the clicked button's value without extra wiring.

Preview
"use client";

import { useRef } from "react";

export default function RenameDialog() {
  const ref = useRef<HTMLDialogElement>(null);

  return (
    <>
      <button
        type="button"
        onClick={() => ref.current?.showModal()}
        className="rounded-md bg-gray-900 px-4 py-2 text-sm font-medium text-white hover:bg-gray-700"
      >
        Rename project
      </button>

      <dialog
        ref={ref}
        onClick={(e) => {
          if (e.target === ref.current) ref.current?.close();
        }}
        aria-labelledby="dialog-title"
        aria-describedby="dialog-description"
        className="m-auto w-full max-w-md rounded-xl p-0 backdrop:bg-gray-900/50"
      >
        <form method="dialog" className="p-6">
          <h2 id="dialog-title" className="text-lg font-semibold text-gray-900">Rename project</h2>
          <p id="dialog-description" className="mt-2 text-sm text-gray-600">Choose a name your team will recognize.</p>

          <label htmlFor="project-name" className="mt-4 block text-sm font-medium text-gray-900">Project name</label>
          <input id="project-name" name="name" type="text" required autoComplete="off" className="mt-1.5 block w-full rounded-md border border-gray-300 px-3 py-2 text-sm text-gray-900 focus:border-gray-900 focus:outline-none focus:ring-1 focus:ring-gray-900" />

          <div className="mt-6 flex justify-end gap-3">
            <button type="button" onClick={() => ref.current?.close()} className="rounded-md border border-gray-300 px-4 py-2 text-sm font-medium text-gray-900 hover:bg-gray-50">Cancel</button>
            <button type="submit" className="rounded-md bg-gray-900 px-4 py-2 text-sm font-medium text-white hover:bg-gray-700">Save name</button>
          </div>
        </form>
      </dialog>
    </>
  );
}

Bottom sheet modal on mobile

Pinned to the bottom edge with a drag-handle cue below the sm breakpoint, and a centered dialog above it.

Preview
"use client";

import { useRef } from "react";

export default function ShareSheet() {
  const ref = useRef<HTMLDialogElement>(null);

  return (
    <>
      <button
        type="button"
        onClick={() => ref.current?.showModal()}
        className="rounded-md bg-gray-900 px-4 py-2 text-sm font-medium text-white hover:bg-gray-700"
      >
        Share
      </button>

      <dialog
        ref={ref}
        onClick={(e) => {
          if (e.target === ref.current) ref.current?.close();
        }}
        aria-labelledby="dialog-title"
        aria-describedby="dialog-description"
        className="m-0 mt-auto w-full max-w-none rounded-b-none rounded-t-2xl p-0 backdrop:bg-gray-900/50 sm:m-auto sm:max-w-md sm:rounded-xl"
      >
        <div className="p-6">
          <div className="mx-auto mb-4 h-1.5 w-10 rounded-full bg-gray-300 sm:hidden" aria-hidden="true"></div>
          <h2 id="dialog-title" className="text-lg font-semibold text-gray-900">Share this page</h2>
          <p id="dialog-description" className="mt-1 text-sm text-gray-600">Anyone with the link can view it.</p>

          <ul className="mt-4 space-y-1">
            <li><button type="button" onClick={() => ref.current?.close()} className="block w-full rounded-md px-3 py-2.5 text-left text-sm text-gray-900 hover:bg-gray-100">Copy link</button></li>
            <li><button type="button" onClick={() => ref.current?.close()} className="block w-full rounded-md px-3 py-2.5 text-left text-sm text-gray-900 hover:bg-gray-100">Send by email</button></li>
            <li><button type="button" onClick={() => ref.current?.close()} className="block w-full rounded-md px-3 py-2.5 text-left text-sm text-gray-900 hover:bg-gray-100">Open in a new tab</button></li>
          </ul>

          <button type="button" onClick={() => ref.current?.close()} className="mt-4 w-full rounded-md border border-gray-300 px-4 py-2 text-sm font-medium text-gray-900 hover:bg-gray-50">Cancel</button>
        </div>
      </dialog>
    </>
  );
}

Side drawer modal

A full-height panel on the right for filters or settings. Still a native modal dialog, so focus trapping and Escape work the same way.

Preview
"use client";

import { useRef } from "react";

export default function FilterDrawer() {
  const ref = useRef<HTMLDialogElement>(null);

  return (
    <>
      <button
        type="button"
        onClick={() => ref.current?.showModal()}
        className="rounded-md bg-gray-900 px-4 py-2 text-sm font-medium text-white hover:bg-gray-700"
      >
        Open filters
      </button>

      <dialog
        ref={ref}
        onClick={(e) => {
          if (e.target === ref.current) ref.current?.close();
        }}
        aria-labelledby="dialog-title"
        className="m-0 ml-auto h-screen max-h-none w-full max-w-sm rounded-none p-0 backdrop:bg-gray-900/50"
      >
        <div className="flex h-full flex-col">
          <div className="flex items-center justify-between border-b border-gray-200 px-6 py-4">
            <h2 id="dialog-title" className="text-lg font-semibold text-gray-900">Filters</h2>
            <button type="button" onClick={() => ref.current?.close()} aria-label="Close filters" className="rounded-md p-2 text-gray-500 hover:bg-gray-100">
              <svg className="h-5 w-5" fill="none" stroke="currentColor" strokeWidth="1.5" viewBox="0 0 24 24" aria-hidden="true"><path strokeLinecap="round" strokeLinejoin="round" d="M6 18 18 6M6 6l12 12" /></svg>
            </button>
          </div>

          <div className="flex-1 overflow-y-auto px-6 py-5">
            <fieldset>
              <legend className="text-sm font-medium text-gray-900">Category</legend>
              <div className="mt-3 space-y-2 text-sm text-gray-700">
                <label className="flex items-center gap-2"><input type="checkbox" className="h-4 w-4 rounded border-gray-300" /> Design</label>
                <label className="flex items-center gap-2"><input type="checkbox" className="h-4 w-4 rounded border-gray-300" /> Engineering</label>
                <label className="flex items-center gap-2"><input type="checkbox" className="h-4 w-4 rounded border-gray-300" /> Marketing</label>
              </div>
            </fieldset>
          </div>

          <div className="flex gap-3 border-t border-gray-200 px-6 py-4">
            <button type="button" onClick={() => ref.current?.close()} className="flex-1 rounded-md border border-gray-300 px-4 py-2 text-sm font-medium text-gray-900 hover:bg-gray-50">Clear</button>
            <button type="button" onClick={() => ref.current?.close()} className="flex-1 rounded-md bg-gray-900 px-4 py-2 text-sm font-medium text-white hover:bg-gray-700">Show results</button>
          </div>
        </div>
      </dialog>
    </>
  );
}

Scrollable modal with sticky header and footer

Long content scrolls inside the panel while the title and actions stay visible. Uses open:flex so the closed dialog stays hidden.

Preview
"use client";

import { useRef } from "react";

export default function TermsDialog() {
  const ref = useRef<HTMLDialogElement>(null);

  return (
    <>
      <button
        type="button"
        onClick={() => ref.current?.showModal()}
        className="rounded-md bg-gray-900 px-4 py-2 text-sm font-medium text-white hover:bg-gray-700"
      >
        Review terms
      </button>

      <dialog
        ref={ref}
        onClick={(e) => {
          if (e.target === ref.current) ref.current?.close();
        }}
        aria-labelledby="dialog-title"
        className="m-auto max-h-[80vh] w-full max-w-lg flex-col rounded-xl p-0 backdrop:bg-gray-900/50 open:flex"
      >
        <div className="flex items-center justify-between border-b border-gray-200 px-6 py-4">
          <h2 id="dialog-title" className="text-lg font-semibold text-gray-900">Terms of service</h2>
          <button type="button" onClick={() => ref.current?.close()} aria-label="Close terms" className="rounded-md p-2 text-gray-500 hover:bg-gray-100">
            <svg className="h-5 w-5" fill="none" stroke="currentColor" strokeWidth="1.5" viewBox="0 0 24 24" aria-hidden="true"><path strokeLinecap="round" strokeLinejoin="round" d="M6 18 18 6M6 6l12 12" /></svg>
          </button>
        </div>

        <div className="min-h-0 flex-1 space-y-3 overflow-y-auto px-6 py-4 text-sm text-gray-600">
          <p>Section 1. These terms describe how the service may be used, what you can expect from us, and what we expect from you. Read each section before continuing.</p>
          <p>Section 2. These terms describe how the service may be used, what you can expect from us, and what we expect from you. Read each section before continuing.</p>
          <p>Section 3. These terms describe how the service may be used, what you can expect from us, and what we expect from you. Read each section before continuing.</p>
          <p>Section 4. These terms describe how the service may be used, what you can expect from us, and what we expect from you. Read each section before continuing.</p>
          <p>Section 5. These terms describe how the service may be used, what you can expect from us, and what we expect from you. Read each section before continuing.</p>
          <p>Section 6. These terms describe how the service may be used, what you can expect from us, and what we expect from you. Read each section before continuing.</p>
        </div>

        <div className="flex justify-end gap-3 border-t border-gray-200 px-6 py-4">
          <button type="button" onClick={() => ref.current?.close()} className="rounded-md border border-gray-300 px-4 py-2 text-sm font-medium text-gray-900 hover:bg-gray-50">Decline</button>
          <button type="button" onClick={() => ref.current?.close()} className="rounded-md bg-gray-900 px-4 py-2 text-sm font-medium text-white hover:bg-gray-700">Accept</button>
        </div>
      </dialog>
    </>
  );
}

What is a 모달 다이얼로그?

모달 다이얼로그는 페이지 위에 열리며 처리되기 전까지 뒤에 있는 모든 요소와의 상호작용을 차단하는 패널입니다. 이 차단 기능이 핵심이며, 삭제 확인이나 필수 단계 완료처럼 결단 없이 진행하면 안 되는 순간을 위한 것입니다. 중단을 일으킬 필요가 없는 모든 기능은 대신 페이지, 패널, 또는 토스트여야 합니다.

모달은 올바르게 구현하기 악명 높을 정도로 어렵기 때문에 수많은 라이브러리가 존재합니다. 제대로 구현해야 하는 목록은 깁니다. 열릴 때 포커스가 다이얼로그 안으로 이동해야 하고 닫힐 때 트리거로 돌아가야 하며, 탭 이동이 뒤쪽 페이지로 탈출하지 않고 패널 내에서 순환해야 하고, 뒤쪽 페이지는 스크롤되지 않아야 하며, Esc로 닫히고, 다이얼로그는 이름과 역할과 함께 안내되어야 하며, 열려 있는 동안 아래의 모든 것은 보조 기술로부터 숨겨져야 합니다.

이제 네이티브 dialog 엘리먼트가 이 모든 것을 거의 처리해 줍니다. 여기에서 showModal을 호출하면 포커스가 갇히고, 백드롭 가상 엘리먼트가 렌더링되며, 나머지 문서는 inert 상태가 되고, Esc가 닫기 동작에 연결됩니다. 이는 예전에는 수백 줄의 세심한 자바스크립트가 필요했던 동작입니다. 브라우저 지원 범위가 2022년부터 넓어졌기 때문에 새로 작업할 때 수제 버전을 정당화하기 어렵습니다.

플랫폼에서 제공하지 않는 기능은 백드롭 클릭으로 닫기입니다. 백드롭은 리스닝할 수 있는 노드가 아니라 가상 엘리먼트이기 때문입니다. 우회 방법은 다이얼로그 자체의 클릭을 리스닝하고 클릭 대상이 내부의 무언가가 아니라 다이얼로그인지 확인하는 것입니다. 다이얼로그 엘리먼트를 직접 누른 클릭은 패널 외부의 패딩 영역(사용자 관점에서는 백드롭)에서 온 것입니다.

Anatomy

트리거
다이얼로그를 여는 버튼입니다. 닫힐 때 포커스가 여기에 자동으로 돌아오므로, 트리거는 핸들러가 있는 div 대신 실제 버튼이어야 합니다.
Dialog 엘리먼트
네이티브 dialog입니다. 너비 제약과 백드롭 스타일링이 적용되며, 내부 컨테이너가 간격을 제어할 수 있도록 패딩은 0으로 설정됩니다.
백드롭
별도의 엘리먼트가 아니라 backdrop 가상 클래스를 통해 스타일링됩니다. showModal로 다이얼로그가 열렸을 때만 존재합니다.
제목
aria-labelledby로 연결된 다이얼로그의 접근 가능한 이름입니다. 카테고리 레이블이 아닌 질문이나 작업 형식으로 작성하세요.
설명
aria-describedby로 연결된 선택적 부가 텍스트입니다. 파괴적인 작업의 경우 결과가 여기에 표시됩니다.
액션 영역
푸터 버튼들로, 엄지손가락과 시선의 도달점에 가장 가깝게 위치하도록 주 액션 또는 파괴적인 액션을 맨 오른쪽에 배치합니다.

How to Use

  1. 1

    마크업 복사

    정적 페이지용 HTML 버전 또는 컴포넌트 트리용 React 래퍼를 가져가세요. 둘 다 내부적으로 동일한 네이티브 엘리먼트를 사용합니다.

  2. 2

    showModal로 열기

    show 대신 showModal을 호출하세요. 일반 show 메서드는 백드롭, 포커스 트랩, 그리고 나머지 페이지를 inert로 만드는 과정 없이 다이얼로그를 엽니다.

  3. 3

    닫기 경로 연결

    Escape 키는 브라우저가 처리합니다. 닫기 버튼과 백드롭 클릭 핸들러를 추가하여 총 3가지 방법으로 나갈 수 있게 하고, 이들 모두 동일한 onClose를 통해 라우팅하세요.

  4. 4

    다이얼로그 레이블 지정

    title의 id를 aria-labelledby에 지정하고, 설명이 있는 경우 description을 aria-describedby에 지정하세요. 이름이 없으면 다이얼로그가 레이블 없는 다이얼로그로 안내됩니다.

  5. 5

    패널 스타일링

    다이얼로그 자체 대신 내부 컨테이너에 패딩을 설정하여 백드롭 클릭 확인이 안정적으로 유지되도록 하세요. 다이얼로그에 패딩을 주면 클릭 영역의 일부가 되어버립니다.

Features

네이티브 포커스 트래핑

포커스는 열릴 때 다이얼로그 안으로 이동하며 내부를 순환합니다. 개발자가 직접 유지 관리해야 하는 keydown 리스너 대신 브라우저가 처리합니다.

트리거로 포커스 반환

닫힐 때 포커스는 다이얼로그를 연 요소로 자동 돌아가므로 키보드 사용자가 중단했던 곳부터 다시 이어서 작업할 수 있습니다.

별도의 요소가 필요 없는 백드롭

백드롭은 backdrop variant로 스타일이 지정된 가상 요소(pseudo-element)이므로, 위치를 잡거나 스택을 쌓거나 동기화 상태를 유지할 별도의 오버레이 div가 필요 없습니다.

Escape 키로 닫기

요소에 내장되어 있습니다. React 래퍼는 결과로 발생하는 close 이벤트를 수신하므로 브라우저가 자체적으로 다이얼로그를 닫을 때 open prop이 동기화 상태를 유지합니다.

페이지의 나머지 부분은 inert 상태가 됨

모달 다이얼로그 뒤의 콘텐츠는 포커스를 받을 수 없으며, 일일이 aria-hidden을 설정하지 않아도 보조 기술에서 숨겨집니다.

백드롭 클릭으로 닫기

클릭 대상 확인 기능이 패딩 영역과 패널 콘텐츠를 구분하여, 별도의 오버레이 노드 없이도 사용자가 기대하는 닫기 동작을 제공합니다.

Common Uses

파괴적인 작업 확인

계정, 프로젝트 또는 파일 삭제 - 우발적인 클릭이 토스트 메시지로 되돌릴 수 없는 결과를 초래하는 경우.

간단한 폼

항목 이름 변경, 팀원 초대, 또는 단일 값 입력 등 사용자를 별도의 페이지로 이동시키면 작업 위치를 잃어버리게 되는 경우.

필수 온보딩 단계

업데이트된 약관 동의나 워크스페이스 선택 등 계속 진행하기 전에 반드시 완료해야 하는 단계.

미디어 및 상세 뷰

현재 페이지 위에 더 큰 이미지나 레코드의 세부 정보를 표시하며, 동일한 스크롤 위치로 돌아가는 것이 중요한 경우.

Accessibility

Customization

Props

PropTypeDefaultDescription
open *boolean-다이얼로그가 표시되는지 여부입니다. 컴포넌트는 엘리먼트를 조건부 렌더링하는 대신 이 값을 네이티브 showModal 및 close 메서드와 동기화합니다.
onClose *() => void-Esc 키, 백드롭 클릭, 닫기 버튼 등 어떤 경로로든 다이얼로그가 닫힐 때 호출됩니다. open 값을 다시 false로 설정하는 데 사용하세요.
title *string-aria-labelledby를 통해 연결되는 다이얼로그의 접근 가능한 이름입니다. 절대 생략하지 마세요. 이름이 없는 다이얼로그는 단순히 다이얼로그로만 안내됩니다.
descriptionstring-aria-describedby를 통해 연결되는 선택적 부가 텍스트로, 건너뛰어지는 대신 제목 바로 다음에 읽힙니다.
childrenReactNode-다이얼로그의 본문과 액션입니다. 탭 순서가 액션에 도달하기 전에 콘텐츠를 거치도록 액션을 가장 마지막에 배치하세요.

Why Use These 모달 다이얼로그s?

직접 구현하는 대신 플랫폼의 기능을 활용합니다. 포커스 트래핑, 비활성화된 백그라운드, Escape 키 처리 등은 직접 만든 모달에서 흔히 놓치는 부분인데, 여기서는 개발자가 아닌 브라우저가 이를 담당합니다.

또한 의존성이 없음을 의미합니다. 헤드리스 다이얼로그 라이브러리도 합리적인 선택이지만, 확인 프롬프트의 경우 요소가 이미 제공하는 동작을 위해 패키지를 추가하고, 버전을 추적하고, API를 배워야 함을 뜻합니다.

React 래퍼는 조건부 렌더링 방식 대신 요소 자체의 상태와 동기화되므로, Escape로 닫힌 다이얼로그도 onClose를 정상적으로 호출하며 open prop이 화면에 표시된 상태와 어긋나지 않습니다.

Tips

Frequently Asked Questions

Related Components