Coding exercise: build a reusable modal component in React.

React practical coding · Freshers

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

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