Build an accessible modal with overlay, focus trap and Esc-to-close.
Skip to solutionKEEP THE
mediumMachine Coding
Build a Modal dialog
260 views
01
Understand the problem
ReactPortalsAccessibility
02
Attempt it yourself
Sketch your approach before reading the solution — that's what interviews test.
Nudge consolestandby
Stuck? Beam a request up — the console returns a conceptual nudge that guides your logic without spoiling the implementation.
03
Study the solution
Solve in
Building a Modal Dialog in React
Mental model: A modal is conditionally-rendered overlay + content, plus three behaviours that make it accessible: close on Escape, close on backdrop click (but not content click), and lock background scroll while open. Keep it controlled — the parent owns open.
Step 1 —
Solution ready — 2 min read
Classified // press E to declassify
04
React solution
Complete solutionRun Playground
import React, { useState } from 'react';
import Modal from './src/Modal';
export default function App() {
const [open, setOpen] = useState(false);
return (
<div style={{ fontFamily: 'sans-serif', padding: 20 }}>
<h1>Modal Demo</h1>
<button onClick={() => setOpen(true)} style={{ padding: '8px 16px', cursor: 'pointer' }}>
Open modal
</button>
<Modal open={open} onClose={() => setOpen(false)} title="Confirm action">
<p>Are you sure you want to continue? This is a controlled modal.</p>
<div style={{ display: 'flex', gap: 8, justifyContent: 'flex-end' }}>
<button onClick={() => setOpen(false)} style={{ padding: '6px 14px', cursor: 'pointer' }}>Cancel</button>
<button onClick={() => setOpen(false)} style={{ padding: '6px 14px', cursor: 'pointer', background: '#2563eb', color: '#fff', border: 'none', borderRadius: 4 }}>Confirm</button>
</div>
</Modal>
</div>
);
}05
Join the discussion
Discussion (0)
Sign in to join the discussion.
No responses yet. Be the first to share what you think.
Transmission complete // awaiting log
KEEP THE
STREAK ALIVE.
Dossier 53 of 87 decoded in the Frontend Machine Coding track. One more won't hurt.