MeDo

Gerador de Modal com IA.

Descreva o diálogo que você precisa e o MeDo gera o conjunto inteiro — cabeçalho, corpo com scroll e rodapé de ações, além de captura de foco, restauração do foco ao fechar, bloqueio de scroll do body e uma variante bottom sheet para mobile.

Modal
Modal

A parte difícil de um modal é a página atrás dele

Um modal parece uma caixa centralizada com sombra, e é justamente por isso que ele é reconstruído de forma malfeita tantas vezes. A camada visual é trivial; a parte difícil vive inteiramente fora do componente. Abrir um diálogo precisa congelar o documento abaixo, capturar o foco do teclado para que o Tab não vagueie até conteúdo oculto, esconder o resto da página das tecnologias assistivas e, ao fechar, devolver o foco exatamente ao elemento que o abriu. Se essa última etapa falha, quem usa teclado é levado silenciosamente ao topo do documento sem saber onde está. Gerar o diálogo junto com seu contrato de foco significa que essa máquina de estados está correta na primeira renderização, em vez de ser remendada depois de uma rodada de QA.

6 modelos

Modelos de Modal que você pode gerar

Cada modelo é um prompt real, não uma captura de tela. Copie para qualquer editor de IA, ou rode no MeDo e receba código React + Tailwind.

BasicHeader + Footer

Composable Dialog With Focus Management

The base every other dialog extends. The visual layer takes minutes; the focus contract is the part worth generating rather than hand-writing.

Create a modal dialog with three sizes — sm 400px, md 560px, lg 760px — centered over a black backdrop at 50 percent opacity, 16px radius, soft shadow. Compose it from Header, Body and Footer slots: the header holds a title and an icon-only close button with an aria-label, the body scrolls independently at max-height 70vh, and the footer right-aligns Cancel next to a primary action. On open, move focus to the first interactive element, trap Tab and Shift+Tab inside the dialog, and lock body scroll by compensating for the scrollbar width so the page does not shift. Set role="dialog", aria-modal="true" and aria-labelledby pointing at the title, and restore focus to the trigger on close.

Teste no MeDo
ConfirmationDestructive Confirm

Non-Dismissible Delete Dialog

The one dialog that must ignore Escape and backdrop clicks. A stray click outside the box should never be the gesture that deletes an account.

Create a destructive confirmation dialog: a warning icon, a heading naming the exact resource, a body stating what will be lost and whether it is recoverable, and a footer with Cancel on the left and a red Confirm on the right. Ignore both Escape and backdrop clicks so the action requires a deliberate button press. Move initial focus to Cancel rather than Confirm, so a stray Enter keypress cancels instead of destroying. Use role="alertdialog" with aria-describedby on the body text. Add an optional type-to-confirm mode requiring the resource name to be typed before Confirm enables, with the comparison case-sensitive and trimmed.

Teste no MeDo
FormForm Dialog

Scrolling Form With Sticky Actions

A long form in a dialog needs a body that scrolls under a fixed header and footer, plus an unsaved-changes guard. Losing typed input to a misclick is unforgivable.

Create a form dialog with a fixed header, a scrolling body and a sticky footer holding Cancel and Save. Keep the header and footer outside the scroll container so the actions stay reachable in a long form. Add a dirty-state guard: when any field has changed, intercept Escape and backdrop clicks and show a nested confirm-discard step inside the same dialog rather than opening a second overlay. On validation failure, move focus to the first invalid field and scroll it into view inside the body. Set aria-busy while saving, disable Save without removing it from the tab order, and close only after the request resolves.

Teste no MeDo
MobileBottom Sheet

Sheet That Slides Up on Phones

A centered card on a phone leaves the buttons floating mid-screen, away from the thumb. Same component, different layout under 640px.

Create a dialog that renders as a centered card above 640px and as a bottom sheet below it: full width, rounded top corners only, sliding up from the bottom edge with a 250ms ease-out transform. Add a drag handle at the top and support swipe-to-dismiss with a velocity threshold, falling back to the close button for keyboard and assistive technology. Cap the sheet height at 90vh with the body scrolling inside, and use dynamic viewport units so the mobile browser chrome does not clip the footer. Keep focus trapping and scroll lock identical in both layouts, and disable the slide animation under prefers-reduced-motion.

Teste no MeDo
PlatformNative Dialog

HTML dialog With showModal

The browser already ships focus trapping, top-layer stacking and Escape handling. Choose this and you delete most of the code the custom overlay needed.

Create a modal built on the native HTML dialog element opened with showModal(), so the browser supplies focus trapping, Escape handling and top-layer stacking with no z-index management. Style the backdrop through the ::backdrop pseudo-element. Add the parts the platform does not give you: body scroll lock on open, an entry and exit animation using allow-discrete and the transition-behavior property, and a close-on-backdrop handler that compares the click target to the dialog element rather than its children. Listen for the close event to restore focus and read returnValue, and use autofocus on the element that should receive focus first.

Teste no MeDo
OverlayCommand Palette

Cmd+K Search Dialog

A modal whose focus stays in the input while arrow keys drive a list elsewhere. Roving focus would break typing, so this one runs on aria-activedescendant.

Create a command palette dialog opened by Cmd+K or Ctrl+K: a search input at the top with results grouped by section below, positioned near the top of the viewport rather than vertically centered. Keep DOM focus in the input at all times and move the visual selection with aria-activedescendant so arrow keys navigate the list without stealing focus from typing. Support Enter to run the highlighted command, Escape to close with focus restored to the previously active element, and a scroll-into-view on the highlighted row. Debounce the query, render an empty state naming what was searched for, and announce the result count through a polite live region.

Teste no MeDo

Como personalizar seu Modal

Diga quais diálogos não podem ser dispensáveis

Escape e cliques no backdrop são o padrão correto para diálogos informativos, mas são um risco em confirmações destrutivas e formulários de várias etapas com dados não salvos. Nomeie as variantes que devem ignorar ambos, para que um clique perdido fora da caixa não apague uma conta.

Peça restauração de foco, não apenas captura de foco

A maioria dos prompts acerta a captura e esquece a viagem de volta. Especifique que o foco volta ao elemento acionador ao fechar, e que o diálogo guarda essa referência ao abrir, para que quem usa teclado retome exatamente de onde parou.

Escolha centralizado ou bottom sheet por breakpoint

Um diálogo centralizado no celular deixa os botões de ação flutuando no meio da tela, longe do polegar. Peça um bottom sheet abaixo de 640px com a ação principal ao alcance, e mantenha o layout centralizado para viewports mais largas.

Nunca abra um modal de dentro de um modal

Um segundo diálogo empilhado sobre o primeiro quebra a captura de foco, dobra o backdrop e deixa ambíguo qual camada o Escape fecha. Peça conteúdo em etapas dentro de um único diálogo, para que o overlay siga sendo uma camada só, com um único dono do foco.

Quem usa o componente Modal

Produto SaaS

Um diálogo de confirmação não dispensável para cancelar uma assinatura, com o nome do plano repetido no corpo e um botão Confirmar vermelho, ao lado de um diálogo mais leve e dispensável para convidar um colega de equipe.

Loja de e-commerce

Um diálogo de visualização rápida com imagens do produto, seletor de tamanho e botão Adicionar ao carrinho, renderizado como bottom sheet em celulares para que as opções de tamanho e o botão do carrinho fiquem ao alcance do polegar.

Dashboard ou ferramenta de administração

Uma confirmação de exclusão em massa que informa a contagem exata de registros e exige digitar o nome do recurso antes de habilitar Confirmar, junto a um diálogo de edição cujo formulário longo rola entre cabeçalho e rodapé fixos.

Site de conteúdo ou mídia

Um diálogo lightbox para imagens em tamanho real com navegação pelas setas, Escape para fechar e o foco retornando à miniatura que o abriu, para que a posição de leitura na galeria nunca se perca.

Padrões de Modal para diferentes sites

O mesmo componente modal, ajustado ao tipo de site em que ele entra.

01 / 06

SaaS Product Dialogs

Two classes of dialog with opposite dismissal rules: invite-a-teammate should close on Escape and backdrop click, cancel-my-subscription should close on neither. Decide that per variant rather than globally, because a single dismissal policy across a product means either annoying dialogs or destroyed data.

Estilos e variações de Modal

Escolha a variação que combina com o resto da página e gere-a.

01 / 06

Centered Dialog

The default above 640px: a fixed-width card centered over a dimmed backdrop. Cap the height at around 70vh with the body scrolling internally, because a dialog taller than the viewport pushes its own footer out of reach and there is no page scroll left to recover it.

Modal em React, Next.js, Vue e Svelte

React, Next.js, Vue 3, SvelteKit, Astro ou HTML puro — o mesmo modal, seis formas de integrar.

01 / 06

React Modal

Render through a portal so the dialog escapes any ancestor with overflow hidden or a transform, both of which would clip it. Store the trigger element on open and focus it again in the cleanup, which is the step most hand-rolled modals skip.

src/components/Modal.tsx

export function Modal({ open, onClose, children }) {
  const trigger = useRef(null)

  useEffect(() => {
    if (!open) return
    trigger.current = document.activeElement
    return () => trigger.current?.focus()
  }, [open])

  if (!open) return null
  return createPortal(
    <div role="dialog" aria-modal="true">{children}</div>,
    document.body
  )
}

Como adicionar o seu Modal a um projeto

Quatro passos, de escolher um modelo de modal até subir para produção.

01~30s

Pick a Dialog Template

Scan the six templates and start from the interaction — a destructive confirm, a scrolling form, a mobile bottom sheet, or a Cmd+K palette.

02~10s

Copy the Prompt

Take the prompt into MeDo, Lovable, Bolt, v0 or Cursor. State whether this dialog may be dismissed by Escape and backdrop click before you run it, since that single decision separates a helpful overlay from one that deletes data on a misclick.

03~1min

Generate and Refine

You get React + Tailwind back with a live preview. Follow up in plain English — "make it a bottom sheet under 640px", "focus Cancel first", "build it on the native dialog element" — rather than rewiring the focus trap yourself.

04~2min

Test It With the Keyboard Only

Open it, Tab to the end and confirm focus cycles instead of escaping into the page, then close it and check focus returned to the trigger. Those two checks catch nearly every modal defect that ships.

Perguntas comuns sobre Modal

Como gerar um componente modal com IA?

Descreva o layout, os tamanhos e as regras de fechamento em um único prompt — por exemplo "um diálogo centralizado de 560px com corpo rolável, ações Cancelar e Confirmar e uma variante destrutiva que ignora Escape". O MeDo gera o componente com captura de foco, restauração de foco, bloqueio de scroll e semântica de diálogo incluídos, então você recebe um overlay que funciona, não uma div estilizada.

O que é captura de foco e por que um modal precisa dela?

A captura de foco mantém Tab e Shift+Tab circulando pelos elementos interativos dentro do diálogo em vez de escapar para a página abaixo. Sem ela, quem navega pelo teclado passa do botão Confirmar para links que não consegue ver, o que confunde e configura falha de WCAG. A captura deve vir acompanhada da restauração de foco, devolvendo o foco ao elemento acionador quando o diálogo fecha.

Um modal deve fechar ao clicar no backdrop?

Para diálogos informativos e de baixo risco, sim — clique no backdrop e Escape são os padrões de dispensa que as pessoas esperam. Para confirmações destrutivas e formulários com dados não salvos, não: um clique acidental fora da caixa não deve apagar dados nem descartar o que foi digitado. Exija o clique explícito em um botão para qualquer coisa irreversível.

Posso usar o elemento nativo <dialog> do HTML em vez de um modal customizado?

Muitas vezes sim. O elemento nativo <dialog> com showModal() entrega captura de foco, tratamento de Escape, empilhamento na top layer e um pseudoelemento ::backdrop de graça, sem gerenciar z-index. Você ainda precisa bloquear o scroll do body e animá-lo por conta própria, e navegadores antigos exigem um fallback. Diga ao MeDo que você quer o elemento nativo e ele construirá em cima dele em vez de reimplementar o comportamento.

Como um modal deve se comportar no mobile?

Abaixo de aproximadamente 640px, um bottom sheet normalmente vence o card centralizado: ancora a ação principal perto do polegar, usa a largura toda para os campos do formulário e respeita a convenção de plataforma que os usuários já conhecem. O MeDo pode gerar os dois layouts em um componente e alternar entre eles no breakpoint que você indicar.

Um modal precisa de role="dialog" e aria-modal?

Sim, a menos que você use o elemento nativo <dialog>, que já fornece a semântica. Um overlay customizado precisa de role="dialog", aria-modal="true" e ou aria-labelledby apontando para o título visível ou aria-label quando não há título visível. Sem aria-modal, os leitores de tela continuam expondo a página atrás do overlay como conteúdo navegável.