MeetCode - Programming Platform | MeetCode - Programming Solutions Platform

ReactJS Program to Close On Escape with Explanation

ReactJS Hard Hooks & Effects 29 views
This problem helps you practice core ReactJS fundamentals in a practical way. It builds intuition around close, escape, react. Let’s break it down step by step so you can implement it confidently.
Back to Questions

Problem Statement

Close a modal-like box when user presses Escape.

Input Format

No input.

Output Format

Render a React component.

Constraints

Attach a keydown listener in useEffect and clean it up.

Code Solution

This explanation is written for learning purposes and to help beginners understand the concept clearly.
import React, { useEffect, useState } from 'react'; function Overlay({ open, onClose }) { useEffect(() => { if (!open) return; function onKey(e) { if (e.key === 'Escape') onClose(); } window.addEventListener('keydown', onKey); return () => window.removeEventListener('keydown', onKey); }, [open, onClose]); if (!open) return null; return ( <div style={{ position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.35)', display: 'grid', placeItems: 'center', padding: 16 }}> <div style={{ width: 'min(92%, 420px)', background: '#fff', borderRadius: 16, padding: 16 }}> <strong>meetcode overlay</strong> <div style={{ marginTop: 10, color: '#555' }}>Press Escape to close.</div> <button type='button' onClick={onClose} style={{ marginTop: 12, padding: '8px 12px', borderRadius: 12, border: 0, background: '#0b5', color: '#fff' }}>Close</button> </div> </div> ); } export default function App() { const [open, setOpen] = useState(false); return ( <div style={{ padding: 16 }}> <button type='button' onClick={() => setOpen(true)} style={{ padding: '10px 14px', borderRadius: 12, border: 0, background: '#0b5', color: '#fff' }}>Open</button> <Overlay open={open} onClose={() => setOpen(false)} /> </div> ); }

Output Example

No sample I/O is provided for this question.

Common Mistakes

- Misreading input/output format.
- Not handling constraints and edge cases.
- Off-by-one errors in loops.
- Forgetting to reset variables between test cases (if any).

Notes & Extra Practice

Solutions (0)

No solutions submitted yet. Be the first!

Prev Next