Coding exercise: build a reusable modal component in React.
Model answer
Render it through a portal so it sits above everything, close on Escape and on a click outside, and keep it accessible with role="dialog" and aria-modal. Move focus into it when it opens.
function Modal({ open, onClose, title, children }) {
const ref = useRef(null);
useEffect(() => {
if (!open) return;
const onKey = (e) => e.key === 'Escape' && onClose();
document.addEventListener('keydown', onKey);
ref.current?.focus();
return () => document.removeEventListener('keydown', onKey);
}, [open, onClose]);
if (!open) return null;
return createPortal(
<div className="backdrop" onClick={onClose}>
<div ref={ref} tabIndex={-1} role="dialog" aria-modal="true" aria-label={title}
onClick={(e) => e.stopPropagation()}>
<h2>{title}</h2>
{children}
<button onClick={onClose}>Close</button>
</div>
</div>,
document.body
);
}Because the content comes in as children, the same component works for confirmations, forms and messages. A full answer also returns focus to the button that opened it and stops the page behind from scrolling.
Tips
- createPortal comes from react-dom.
Practise it yourself in the React and Angular code playground.
Learn this topic
React.js Full Course: Beginner to Advanced .
Sign in to add your own answer.
More questions
- Coding exercise: build a Todo application in React.
- Coding exercise: create a search box with debounce in React.
- Coding exercise: fetch API data and display it in a table in React.
- Coding exercise: implement pagination in React.
- Coding exercise: create a login form with validation in React.
- Coding exercise: build a parent-child communication example in React.