Back to cookbook

AI Prompt to Build an Accessible React Modal Component

17 views Published

Make this prompt yours

Share

This prompt generates an accessible React modal component, built for frontend developers who need a dialog that actually works with keyboards and screen readers instead of just looking right visually. Modals are deceptively easy to get wrong: focus often escapes behind the overlay, the Escape key does nothing, and screen readers announce the whole page instead of the dialog content.

The prompt specifies the accessibility behavior up front rather than leaving it as an afterthought: focus trapping inside the modal while it's open, returning focus to the triggering element on close, closing on Escape and on an overlay click, and the correct role and aria-* attributes so assistive technology announces the dialog properly. It also asks for the component to be unstyled or minimally styled so it drops into an existing design system without fighting your CSS.

Because accessibility bugs in interactive components are easy to miss in a quick visual review, it's worth testing the generated code with a keyboard-only pass (Tab, Shift+Tab, Escape) before shipping it.

Prompt template

Make this prompt yours

prompt-template
237 tokens
ROLE: You are a senior frontend engineer writing accessible React components. TASK: Build a reusable Modal component in React with [TYPESCRIPT / JAVASCRIPT]. FUNCTIONAL REQUIREMENTS: - Opens and closes based on an `isOpen` prop and `onClose` callback - Renders via [REACT PORTAL / INLINE] into [TARGET DOM NODE OR DESCRIPTION] - Closes on Escape key press - Closes on clicking the overlay background (but not when clicking inside the modal content) ACCESSIBILITY REQUIREMENTS: - Traps keyboard focus inside the modal while it is open - Returns focus to the element that triggered the modal when it closes - Uses `role="dialog"`, `aria-modal="true"`, and `aria-labelledby` pointing to the modal title - Prevents background content from being read by screen readers while the modal is open STYLING: - [UNSTYLED WITH CLASS NAMES / USE TAILWIND / MATCH THIS DESIGN SYSTEM: DESCRIBE] OUTPUT FORMAT: Provide the complete component code in a single file, followed by a short usage example showing how to open the modal from a parent component.

Want it sharper? Optimize this prompt with Prompt Optimizer, check it with the Prompt Debugger or shorten it with the Token Optimizer.

Example input

example-input
198 tokens
ROLE: You are a senior frontend engineer writing accessible React components. TASK: Build a reusable Modal component in React with TypeScript. FUNCTIONAL REQUIREMENTS: - Opens and closes based on an isOpen prop and onClose callback - Renders via a React portal into document.body - Closes on Escape key press - Closes on clicking the overlay background (but not when clicking inside the modal content) ACCESSIBILITY REQUIREMENTS: - Traps keyboard focus inside the modal while it is open - Returns focus to the element that triggered the modal when it closes - Uses role="dialog", aria-modal="true", and aria-labelledby pointing to the modal title - Prevents background content from being read by screen readers while the modal is open STYLING: - Unstyled, with plain class names (modal-overlay, modal-content) so I can style it myself OUTPUT FORMAT: Provide the complete component code in a single file, followed by a short usage example.

When to use it

  • Building a confirmation dialog, settings panel, or image lightbox that needs to meet accessibility requirements
  • Replacing a third-party modal library with a lightweight custom component
  • Auditing an existing modal that doesn't trap focus or respond to the Escape key
  • Teaching a junior developer what a fully accessible modal implementation actually requires

Best practices

  • Explicitly ask for focus trapping and focus return behavior; most generated components skip this unless asked directly
  • Specify whether you're using React state, a portal (createPortal), or a specific library convention your codebase already follows
  • Request keyboard behavior (Escape to close, Tab cycling) as a named requirement, not an assumption
  • Ask for the component to be unstyled or styled with plain CSS classes so it's easy to adapt to your existing design system
  • If you're converting a design file into this component visually, Site to Prompt can turn a real rendered reference page into a structured prompt describing its layout and spacing

Common mistakes

  • Not asking for focus trapping, which lets keyboard users Tab out of an open modal into the page behind it
  • Forgetting to specify that focus should return to the trigger button when the modal closes
  • Leaving out the Escape key handler, which many users expect as a standard way to close any dialog
  • Over-specifying visual styling in the prompt instead of behavior, resulting in a component that looks right but fails basic accessibility checks

FAQs

How do I make a React modal accessible to screen readers?

Use role="dialog" and aria-modal="true" on the modal container, point aria-labelledby at the modal's title element, and make sure focus moves into the modal when it opens so screen readers announce it correctly.

What is focus trapping and why does a modal need it?

Focus trapping keeps keyboard Tab navigation cycling within the modal's interactive elements instead of letting it escape into the page behind the overlay, which would otherwise confuse keyboard and screen reader users about what's currently open.

Should a modal close on Escape key by default?

Yes, closing on Escape is a widely expected behavior for dialogs and should be included unless the modal requires an explicit confirmation action before closing, such as a form with unsaved changes.

Can ChatGPT or Claude generate a modal that works with an existing design system?

Both can generate a modal styled to match a described design system if you specify the class names, CSS framework, or component library conventions in the prompt rather than leaving styling unspecified.

What tool can help me verify this generated prompt covers all the edge cases?

Prompt Debugger — scans the prompt for missing constraints or vague requirements, such as unspecified keyboard behavior, before you use it to generate production code.

Found this prompt useful? Share it.

Share

More in React Prompt Recipes

React Prompt Recipes

AI Prompt to Build a React Billing Dashboard Component Using Stripe's MCP Server

This prompt is for frontend developers who need to build a React billing dashboard component that shows a customer's live subscription, invo…

ROLE:
You are a senior React/TypeScript developer building a billing dashboard component for a SaaS product.

CONTEXT:
The component should display billing data for a customer, retrieved via Stripe's MCP server: [LIST_DATA_NEEDED_E.G._SUBSCRIPTION_PLAN_NEXT_CHARGE_DATE_PAYMENT_METHOD_RECENT_INVOICES]
Framework/styling: [REACT_VERSION_AND_STYLING_APPROACH_E.G._TAILWIND_CSS_MODULES]

CONSTRAINTS:
- Handle these billing states explicitly: [LIST_STATES_E.G._ACTIVE_PAST_DUE_CANCELED_PENDING_NO_PAYMENT_METHOD]
- Show a loading skeleton while data is being fetched, and a clear error state if the fetch fails
- Format currency and dates using the customer's actual locale/currency, not a hardcoded format
- Separate the data-fetching hook from the presentational component

OUTPUT FORMAT:
1. A short explanation of the component's structure (hook + presentational component)
2. The full TypeScript code, in a single fenced code block, with comments marking where each billing state is handled
3. A one-line note on any assumption you made about the data shape returned by the MCP server

Make this prompt yours

React Prompt Recipes

AI Prompt to Build a React Dark Mode Toggle with System Preference Detection

A React dark mode toggle prompt asks ChatGPT, Claude, or Gemini to generate a theme switching component that respects the user's OS level li…

Role: You are a senior React developer building a reusable UI component.

Context:
Framework/setup: [REACT VERSION, e.g. React 18 with Vite, Next.js App Router]
Styling approach: [CSS variables / Tailwind CSS dark class / CSS-in-JS library]
Component location/usage: [where the toggle will live, e.g. app header, settings page]

Task:
Build a dark mode toggle component with this exact behavior:
1. On first load, detect the user's OS preference via the `prefers-color-scheme` media query and use it as the initial theme, applied before the main content paints (no flash of the wrong theme).
2. If the user has previously made an explicit choice, that stored choice overrides the OS preference on future visits.
3. Persist the user's explicit choice in [STORAGE MECHANISM, e.g. localStorage].
4. Listen for theme changes made in other open tabs and update this tab's theme to match.
5. Expose the current theme and a toggle function via [CONTEXT/HOOK NAME, e.g. a useTheme hook] so other components can read and react to it.

Constraints:
- Use [STYLING APPROACH] to apply the theme, not inline style objects
- Include accessible labeling (aria-label or visible text) that reflects the current state
- Keep the component dependency-free unless [ALLOWED LIBRARIES] are specified

Output format:
Return the full component code in a fenced code block, followed by a short usage example showing how to wrap the app and consume the hook elsewhere.

Make this prompt yours

React Prompt Recipes

AI Prompt to Build a React Kanban Board With Drag-and-Drop

This prompt gives ChatGPT, Claude, or Gemini a complete specification for building a React Kanban board with drag and drop column reordering…

You are a senior React developer specializing in accessible, production-ready UI components.

Context:
- Framework: [REACT VERSION, e.g. React 18 with TypeScript]
- Drag-and-drop library: [LIBRARY NAME, e.g. @dnd-kit/core]
- Styling approach: [e.g. Tailwind CSS, CSS Modules, styled-components]
- Columns or workflow stages: [LIST OF COLUMN NAMES, e.g. Backlog, In Progress, Review, Done]
- State source: [e.g. local state, Zustand store, REST API endpoint]

Build a Kanban board component with the following requirements:
1. Render one column per workflow stage listed above, each showing its card count
2. Support dragging cards between columns and reordering cards within a column
3. Support keyboard-based reordering, not mouse-only interaction, for accessibility
4. Identify cards by a stable [ID FIELD NAME] field, never by array index
5. Call a [CALLBACK NAME] function on every successful move, passing the card id, source column, destination column, and new index
6. Show an optimistic UI update immediately, then roll back if [CALLBACK NAME] rejects
7. Handle empty columns and drops outside any valid column gracefully

Output format:
- The main board component
- Column and Card subcomponents
- Any custom hooks used for drag state
- A short usage example showing how to wire [CALLBACK NAME] to a real API call
- Brief notes on any library-specific setup required, such as providers, context, or CSS imports

Make this prompt yours