モーダルダイアログ examples
ネイティブの dialog 要素をベースに構築されたアクセシブルなモーダルで、背景(backdrop)、フォーカストラップ、Escape キーでの閉じる機能を備えています。
ブラウザのネイティブの dialog 要素をベースに構築されたモーダルダイアログ。フォーカストラップ、背景のレンダリング、Escape キーでの閉じる機能が、自分で保守しなければならない JavaScript ではなくプラットフォーム側で提供されます。
背景クリックでの閉じる機能、適切な ARIA ラベリング、および open プロップを要素自体のメソッドに同期させる 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.
"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.
"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.
"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.
"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.
"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 モーダルダイアログ?
モーダルダイアログは、ページの上に開き、対応が完了するまで背後にあるすべての要素とのインタラクションをブロックするパネルです。このブロックすること自体が最も重要であり、削除の確認や必須ステップの完了など、決定を下さずに続行することが不適切な場面で使用されます。割り込みを必要としないものは、代わりにページ、パネル、またはトーストにすべきです。
モーダルは正しく構築することが難しことで悪名高く、そのため非常に多くのライブラリが存在します。正しく実装しなければならない項目のリストは長いです:開いたときにフォーカスがダイアログに移動し、閉じるときにトリガーに戻ること、タブ移動が背後のページに脱出せずパネル内で循環すること、背後のページがスクロールしないこと、Escape キーで閉じられること、ダイアログが名前とロールと共にアナウンスされること、そして開いている間はその下にあるすべてが支援技術から隠されていることです。
現在のネイティブの dialog 要素は、そのほとんどを自動的に処理してくれます。上で showModal を呼び出すと、フォーカスがトラップされ、背景の疑似要素がレンダリングされ、ドキュメントの残りの部分が inert(操作不可)になり、Escape キーで閉じる動作が配線されます。これらは以前なら数百年行の慎重な JavaScript を必要としていた動作です。ブラウザのサポートは 2022 年以降広範に行われており、新規開発で自作バージョンを正当化することは難しくなっています。
プラットフォームが提供してくれないのは、背景クリックによる閉じる機能です。これは背景がリスニング可能なノードではなく疑似要素であるためです。その回避策として、ダイアログ自体でクリックをリッスンし、クリックのターゲットが内部の要素ではなくダイアログ自体であるかどうかを確認します。ダイアログ要素を直接ヒットしたクリックは、パネルの外側のパディング領域(ユーザーから見た背景)から発生したものです。
Anatomy
- トリガー
- ダイアログを開くボタン。閉じるときにフォーカスがここに自動的に戻るため、トリガーはハンドラーを持つ div ではなく、実際のボタンにする必要があります。
- Dialog 要素
- ネイティブの dialog。幅の制約と背景のスタイリングを持ち、内側のコンテナが余白を制御できるようにパディングはゼロに設定されています。
- 背景
- 個別の要素ではなく、backdrop 疑似クラスを通じてスタイリングされます。これは showModal でダイアログが開かれている間のみ存在します。
- タイトル
- aria-labelledby で接続された、ダイアログのアクセシブル名。カテゴリ名としてではなく、質問やタスクとして表現してください。
- 説明
- aria-describedby で接続された、オプションの補足テキスト。破壊的なアクションの場合、ここに結果(影響)を記述します。
- アクション行
- フッターのボタン。親指や視線の終点に最も近くなるよう、プライマリまたは破壊的なアクションを最後に配置して右寄せにします。
How to Use
- 1
マークアップをコピー
静的ページ用の HTML バージョン、またはコンポーネントツリー用の React ラッパーを取得します。どちらも内部では同じネイティブ要素を使用しています。
- 2
showModal で開く
show ではなく showModal を呼び出してください。通常の show メソッドは、背景なし、フォーカストラップなし、そしてページの残りの部分を inert にせずにダイアログを開きます。
- 3
閉じる導線を配線する
Escapeキーの処理はブラウザーが行います。閉じるボタンと背景(backdrop)のクリックハンドラーを追加することで、3つの脱出方法を用意し、それらすべてを同じ onClose にルーティングします。
- 4
ダイアログにラベルを付ける
aria-labelledby にはタイトルの id を、説明がある場合は aria-describedby に説明の id を指定します。名前がない場合、ダイアログはラベルなしのダイアログとしてアナウンスされます。
- 5
パネルをスタイリングする
ダイアログ自体ではなく、内部のコンテナにパディングを設定します。これにより背景クリックの判定が確実に行えるようになります(ダイアログにパディングを設定すると、それ自体がクリック領域に含まれてしまうため)。
Features
ネイティブのフォーカストラップ
開発者が手動で維持管理する必要がある keydown リスナーではなく、ブラウザーによって処理され、開いたときにダイアログ内にフォーカスが移動し、その内部で循環します。
トリガーへフォーカスを戻す
閉じたときに、ダイアログを開いた要素へフォーカスが自動的に戻るため、キーボードユーザーは中断したところから再開できます。
余分な要素のない背景(Backdrop)
背景は backdrop バリアントでスタイル設定された疑似要素であるため、位置合わせ、スタック、同期を維持するための個別のオーバーレイ div は不要です。
Escapeキーで閉じる
要素に組み込まれています。Reactラッパーは結果として発生する close イベントをリッスンするため、ブラウザーが独自にダイアログを閉じたときも open プロップが同期された状態を維持します。
ページの残りの部分が inert(不活性)になる
モーダルダイアログの背後にあるコンテンツはフォーカス不可になり、アシスティブテクノロジーからも隠されます(手動で aria-hidden を設定する必要はありません)。
背景クリックで閉じる
クリック対象の判定によりパディング領域とパネル内容が区別され、余分なオーバーレイノードなしで、ユーザーが期待する閉じる動作を実現します。
Common Uses
破壊的なアクションを確認する
アカウント、プロジェクト、またはファイルの削除など、誤クリックが発生した場合にトースト通知では取り消せない結果を招くケース。
短いフォーム
アイテムの名前変更、チームメイトの招待、または単一の値の入力など、別ページに遷移させるとユーザーの作業位置が失われてしまうケース。
必須のオンボーディングステップ
更新された規約への同意やワークスペースの選択など、続行する前にどうしても完了しなければならないステップ。
メディアおよび詳細ビュー
現在のページの上に大きめの画像やレコードの詳細を表示する場合で、同じスクロール位置に戻ることが重要なケース。
Accessibility
- dialog 要素は暗黙的な dialog ロールを持ち、showModal で開いた場合は暗黙的なモーダル状態を持つため、手動でロールや aria-modal 属性を追加する必要はありません。
- aria-labelledby がタイトルを指定するため、ダイアログは汎用的なダイアログとしてではなく、名前付きでアナウンスされます。
- aria-describedby が補足テキストを指定するため、破壊的なアクションの結果がスキップされずに読み上げられます。
- 開いたときにフォーカスがダイアログに移動し、閉じたときにトリガーに戻ります。どちらもブラウザーによって処理されます。
- ダイアログが開いている間は、ダイアログの外側のすべてが inert(不活性)になるため、タブキーで背後のページに到達できず、スクリーンリーダーもその背後を読み上げません。
- Escapeキーはデフォルトでダイアログを閉じます。これを防がないでください。ダイアログを閉じられては困る場合、その問題は「モーダルにするべきではないインタラクションである」ということです。
- 閉じるボタンには、視覚的なラベルまたは aria-label が必要です。アクセシブルな名前のないアイコンのみの閉じるボタンは、最も一般的なダイアログの欠陥の1つです。
Customization
- backdrop バリアントを使用して背景をスタイリングします。暗くするには backdrop:bg-gray-900/50 を使用し、背後のページをぼかしたい場合はさらに backdrop:backdrop-blur-sm を追加します。
- ダイアログ要素自体ではなく、内部のコンテナにパディングを維持してください。そうしないと、パディングがダイアログのクリック領域の一部になってしまい、背景クリックによる閉じる動作が予測通りに機能しなくなります。
- 小画面では下端に固定し、sm より上では中央揃えの位置に戻すことで、ボトムシートにします。
- open 状態に対する starting-style ルールを使用して、出現時のアニメーションを設定します。200ms未満に抑えてください。モーダルが遅いと、コンテンツが定着するまで読めないため、反応が悪いと感じられます。
- 幅の広いダイアログにするには、max-width を変更します。max-w-2xl を超える場合は、長すぎるモーダルはスクロールしにくく独自のアクションを隠してしまうため、コンテンツを別ページにすべきかどうか検討してください。
Props
| Prop | Type | Default | Description |
|---|---|---|---|
| open * | boolean | - | ダイアログが表示されているかどうか。このコンポーネントは、要素を条件付きでレンダリングするのではなく、状態をネイティブの showModal および close メソッドに同期させます。 |
| onClose * | () => void | - | Escape キー、背景のクリック、閉じるボタンなど、どのような経路でダイアログが閉じられた場合でも呼び出されます。open を false に戻すために使用します。 |
| title * | string | - | aria-labelledby を通して紐付けられた、ダイアログのアクセシブル名。絶対に省略しないでください。名前のないダイアログは単なる「ダイアログ」として読み上げられます。 |
| description | string | - | aria-describedby を通して紐付けられたオプションの補足テキスト。スキップされずにタイトルの後に読み上げられます。 |
| children | ReactNode | - | ダイアログの本文とアクション。タブ移動の順序がアクションに到達する前にコンテンツ内を巡るよう、アクションは最後に配置してください。 |
Why Use These モーダルダイアログs?
独自の再実装ではなく、プラットフォームの機能を利用します。フォーカス トラップ、背面の inert 化、Escape キーの処理は自作モーダルで不具合が起きやすい部分ですが、ここではブラウザ側が処理するため、自前で実装する必要はありません。
つまり、依存関係が不要ということです。ヘッドレスなダイアログ ライブラリも妥当な選択肢ですが、確認プロンプト程度のためにパッケージの導入やバージョン管理を行い、要素が本来持っている挙動のために新しいAPIを学ぶ必要が生じます。
React ラッパーは条件付きレンダリングではなく要素自体のステートと同期するため、Escape キーで閉じられたダイアログでも onClose が正しく発火し、open プロップが画面上の表示とズレることがありません。
Tips
- show ではなく必ず showModal を使用してください。違いはモーダルとしての挙動の有無であり、show を使うと単に上に重なって表示されるだけのパネルになり、その他のモーダル機能は一切ありません。
- ダイアログ自体ではなく、内部のコンテナにパディングを設定してください。そうしないと、パネルの一部に見える部分へのクリックが、背景(backdrop)のクリック判定として誤検知されてしまいます。
- ボタンのアクション名には具体的なラベルを付けます。「プロジェクトを削除」単体で意味が分かりますが、「確認」だけではタイトルの読み上げが必要になり、スクリーン リーダーを使用しているユーザーがフォーカスを失う原因になります。
- モーダルのネスト(入れ子)は避けてください。ダイアログから別のダイアログを開く必要がある場合、2層目を重ねるのではなくフロー全体の再設計が必要です。
- 現在のブラウザでは showModal によって背景のスクロールがすでにロックされるため、その上から overflow-hidden クラスを追加すると、スクロールバーが二重に消えてレイアウト シフト(ズレ)を引き起こす可能性があります。
- キーボード操作のみでテストを行います:開く、すべてのコントロールを Tab キーで移動する、Escape キーを押す。トリガー以外の場所にフォーカスが残る場合、ダイアログを同期するのではなく条件付きでレンダリングしている原因があります。