Alat baru telah ditambahkan! Lihat yang baru

Beranda/Komponen/Modal Dialog

Modal Dialog examples

Modal yang dapat diakses, dibangun di atas elemen dialog native, dilengkapi backdrop, focus trapping, dan tombol Escape untuk menutup.

Dialog modal yang dibangun di atas elemen dialog native browser, sehingga focus trapping, rendering backdrop, dan penutupan dengan Escape berasal dari platform, bukan dari JavaScript yang harus Anda kelola.

Mencakup klik backdrop untuk menutup, pelabelan ARIA yang benar, dan wrapper React yang menyinkronkan prop open ke metode elemen itu sendiri.

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 Modal Dialog?

Modal dialog adalah panel yang terbuka di atas halaman dan memblokir interaksi dengan apa pun di belakangnya hingga diselesaikan. Bagian pemblokiran ini adalah inti utamanya: ini digunakan untuk momen di mana melanjutkan tanpa keputusan adalah hal yang keliru, seperti mengonfirmasi penghapusan atau menyelesaikan langkah yang wajib. Apa pun yang tidak perlu menginterupsi sebaiknya berupa halaman, panel, atau toast.

Modal terkenal sulit dibuat dengan benar, itulah sebabnya ada begitu banyak library untuk komponen ini. Daftar hal yang harus benar sangat panjang: fokus harus berpindah ke dalam dialog saat terbuka dan kembali ke trigger saat ditutup, penekanan tombol tab harus berputar di dalam panel alih-alih keluar ke halaman di belakangnya, halaman di belakang tidak boleh ikut digulir (scroll), Escape harus menutupnya, dialog harus diumumkan dengan nama dan role, dan segala sesuatu di bawahnya harus disembunyikan dari teknologi asistif saat modal terbuka.

Elemen dialog native sekarang menangani hampir semuanya. Memanggil showModal pada elemen tersebut akan mengunci fokus, merender pseudo-element backdrop, membuat sisa dokumen menjadi inert, dan menghubungkan tombol Escape untuk menutup - perilaku yang dulunya memerlukan beberapa ratus baris kode JavaScript yang rumit. Dukungan browser sudah sangat luas sejak 2022, membuat versi rakitan sendiri sulit dibenarkan untuk proyek baru.

Fitur yang tidak disediakan oleh platform adalah klik backdrop untuk menutup, karena backdrop adalah pseudo-element alih-alih node yang dapat Anda pasangi event listener. Solusinya adalah mendengarkan klik pada dialog itu sendiri dan memeriksa apakah target klik adalah dialog itu sendiri alih-alih konten di dalamnya - klik yang mendarat langsung pada elemen dialog berasal dari area padding di luar panel, yang mana merupakan backdrop bagi pengguna.

Anatomy

Trigger
Tombol yang membuka dialog. Fokus dikembalikan ke sini secara otomatis saat ditutup, itulah sebabnya trigger harus berupa tombol sungguhan, bukan div dengan event handler.
Elemen dialog
Dialog native. Membawa batasan lebar (width constraint) dan styling backdrop, dengan padding disetel ke nol agar kontainer bagian dalam yang mengontrol jarak (spacing).
Backdrop
Diberi gaya melalui pseudo-class backdrop alih-alih elemen terpisah. Elemen ini hanya ada saat dialog dibuka dengan showModal.
Title
Nama dialog yang dapat diakses, dihubungkan dengan aria-labelledby. Rumuskan sebagai pertanyaan atau tugas, bukan sebagai label kategori.
Description
Teks pendukung opsional yang dihubungkan dengan aria-describedby. Untuk aksi destruktif, di sinilah konsekuensi dijelaskan.
Action row
Tombol footer, diratakan ke kanan dengan aksi utama atau destruktif di urutan terakhir sehingga berada paling dekat dengan jempol dan titik akhir pandangan mata.

How to Use

  1. 1

    Salin markup

    Gunakan versi HTML untuk halaman statis atau wrapper React untuk pohon komponen (component tree). Keduanya menggunakan elemen native yang sama di baliknya.

  2. 2

    Buka dengan showModal

    Panggil showModal alih-alih show. Metode show biasa membuka dialog tanpa backdrop, tanpa focus trapping, dan tanpa membuat sisa halaman menjadi inert.

  3. 3

    Hubungkan jalur penutup

    Tombol Escape ditangani oleh browser. Tambahkan tombol tutup dan handler klik backdrop agar ada tiga cara keluar, dan arahkan ketiganya melalui onClose yang sama.

  4. 4

    Beri label pada dialog

    Arahkan aria-labelledby ke id judul, dan aria-describedby ke deskripsi jika ada. Tanpa nama, dialog akan diumumkan sebagai dialog tanpa label.

  5. 5

    Atur style panel

    Atur padding pada container bagian dalam alih-alih pada dialog itu sendiri, agar pemeriksaan klik backdrop tetap andal - padding pada dialog akan menjadi bagian dari area kliknya sendiri.

Features

Penangkapan fokus bawaan

Fokus berpindah ke dalam dialog saat dibuka dan berputar di dalamnya, ditangani oleh browser alih-alih oleh listener keydown yang harus Anda kelola sendiri.

Fokus kembali ke trigger

Saat ditutup, fokus otomatis kembali ke elemen yang membuka dialog, sehingga pengguna keyboard dapat melanjutkan dari posisi terakhir mereka.

Backdrop tanpa elemen tambahan

Backdrop adalah pseudo-element yang diberi style dengan varian backdrop, sehingga tidak ada div overlay terpisah yang perlu diposisikan, di-stack, atau disinkronkan.

Escape menutup dialog

Bawaan dari elemen tersebut. Wrapper React mendengarkan event close yang dihasilkan agar prop open tetap sinkron saat browser menutup dialog dengan sendirinya.

Sisa halaman menjadi inert

Konten di balik modal dialog tidak dapat difokuskan dan disembunyikan dari teknologi asistif, tanpa perlu mengatur aria-hidden pada elemen apa pun secara manual.

Klik backdrop untuk menutup

Pemeriksaan target klik membedakan area padding dari konten panel, memberikan perilaku penutupan yang diharapkan pengguna tanpa node overlay tambahan.

Common Uses

Mengonfirmasi tindakan destruktif

Menghapus akun, project, atau file - kasus di mana klik yang tidak disengaja memiliki konsekuensi yang tidak dapat dibatalkan dengan toast.

Form pendek

Mengubah nama item, mengundang rekan tim, atau memasukkan satu nilai, di mana mengirim pengguna ke halaman terpisah akan menghilangkan posisi mereka.

Langkah onboarding wajib

Langkah yang benar-benar harus diselesaikan sebelum melanjutkan, seperti menyetujui pembaruan ketentuan atau memilih workspace.

Tampilan media dan detail

Menampilkan gambar yang lebih besar atau detail record di atas halaman saat ini, di mana kembali ke posisi scroll yang sama adalah hal yang penting.

Accessibility

Customization

Props

PropTypeDefaultDescription
open *boolean-Menentukan apakah dialog sedang ditampilkan. Komponen ini menyinkronkannya ke metode native showModal dan close alih-alih merender elemen secara kondisional.
onClose *() => void-Dipanggil saat dialog ditutup melalui cara apa pun - tombol Escape, klik backdrop, atau tombol tutup. Gunakan ini untuk mengatur open kembali ke false.
title *string-Nama dialog yang dapat diakses, dihubungkan melalui aria-labelledby. Jangan pernah mengabaikannya; dialog tanpa nama akan diumumkan hanya sebagai dialog.
descriptionstring-Teks pendukung opsional, dihubungkan melalui aria-describedby agar dibaca setelah judul dan tidak dilewati.
childrenReactNode-Isi dan aksi dialog. Letakkan aksi di urutan terakhir agar urutan tab melewati konten sebelum mencapai tombol aksi.

Why Use These Modal Dialogs?

Ini menggunakan platform alih-alih mengimplementasikannya ulang. Focus trapping, background inert, dan penanganan Escape adalah bagian yang sering salah dibuat pada modal buatan sendiri, dan di sini hal tersebut menjadi tanggung jawab browser, bukan Anda.

Itu juga berarti tanpa dependensi. Pustaka headless dialog adalah pilihan yang wajar, tetapi untuk sebuah prompt konfirmasi, itu berarti mengunduh package, melacak versinya, dan mempelajari API-nya untuk mendapatkan perilaku yang sudah disediakan oleh elemen tersebut.

Wrapper React melakukan sinkronisasi dengan state elemen itu sendiri alih-alih merendernya secara kondisional, sehingga dialog yang ditutup dengan Escape tetap memicu onClose dan prop open tidak keluar dari sinkronisasi dengan apa yang ada di layar.

Tips

Frequently Asked Questions

Related Components