Frontend School
DashboardProblemsLearnPracticeMock InterviewReportsStatsBuy Credits
DashboardProblemsLearnPracticeMock Interview
Machine Coding Patterns
  1. 1.Setting Up for Machine Coding
  2. 2.Interactive UI Basics: Counter & Toggle
  3. 3.Building a Static Component: Star Rating
  4. 4.Handling User Input: Form Elements
  5. 5.Displaying Dynamic Data: Todo List
  6. 6.Filtering & Searching Data
  7. 7.Pagination & Infinite Scroll
  8. 8.Advanced UI Components: Modals & Tooltips
  9. 9.Drag & Drop Functionality (Basic)
  10. 10.Reusability Patterns: Hooks & HOCs
  11. 11.Performance Optimization Techniques
  12. 12.Complex State Management & Architecture
Machine Coding Patterns
08

Machine Coding · Lesson 8 of 12 · 4 min

Advanced UI Components: Modals & Tooltips

This isn't about building a popup. It's about demonstrating control over the DOM, accessibility, and state management under the pressure of a live coding session.

How to Build a Production-Ready Modal

A modal isn't just a div that appears and disappears. To be correct, it must exist outside the React component tree, be fully controlled by state, and handle user interaction cleanly.

The non-negotiable tool for this is a Portal. Rendering your modal into a portal attached to document.body is the only reliable way to escape stacking context issues caused by a parent's z-index or overflow: hidden. Anything else is a hack that will fail in a complex app.

Your modal should be a controlled component. It takes an isOpen prop and an onClose callback. It does not manage its own visibility state. This makes it predictable and easy to integrate.

The backdrop click-to-close feature is standard. Implement it on the overlay element, but remember to call e.stopPropagation() on the modal content's click handler. Otherwise, any click inside the modal will also close it.

The Three Pillars of Modal Accessibility

This is what separates a junior-level implementation from a senior-level one. Interviewers will specifically test for these.

Pillar 1: Focus Management When the modal opens, the user's focus must move into it. When it closes, focus must return to the element that triggered it. This is not optional.

First, trap the focus. A user tabbing through the modal should cycle through its focusable elements, never escaping to the page behind it. You do this by finding the first and last focusable elements and manually managing focus on Tab and Shift+Tab.

Second, restore the focus. Before the modal opens, store a reference to document.activeElement. In your useEffect cleanup function, call .focus() on that stored element.

The trap: Forgetting to restore focus. It's a jarring user experience and a clear accessibility failure. A keyboard user is now lost on the page, and you've failed the interview question.

Pillar 2: Keyboard Interaction The Escape key must close the modal. This is a universal convention. Implement this with a keydown event listener on the document inside a useEffect. Don't forget to remove the listener in the cleanup function to prevent memory leaks.

Pillar 3: ARIA Attributes These attributes are how you explain your component's behavior to screen readers. They are easy to add and show you're thinking about all users.

  • role="dialog": Tells assistive technology that this is a dialog window.
  • aria-modal="true": Informs it that the underlying page content is inert.
  • aria-labelledby="id-of-title": Points to the modal's title, so it's the first thing announced.

Don't Forget the Side Effects

A modal's lifecycle involves direct DOM manipulation. Handle these effects carefully.

The most common side effect is scroll locking. While the modal is open, the main page <body> must not scroll. The simplest way is to set document.body.style.overflow = 'hidden' when the modal mounts and reset it on unmount.

Every side effect you create in a useEffect must have a corresponding cleanup. If you add an event listener, you must remove it. If you change a body style, you must reset it. This prevents bugs when the component unmounts or re-renders.

This flow shows the lifecycle is more than just rendering. Steps E, F, H, and K are pure side effects and are critical to get right.

The Modal Implementation

This code combines portals, focus trapping, scroll locking, and ARIA attributes. It's what you should aim to reproduce in an interview.

import React, { useEffect, useRef } from 'react';
import ReactDOM from 'react-dom';

interface AccessibleModalProps {
  isOpen: boolean;
  onClose: () => void;
  title: string;
  children: React.ReactNode;
}

const AccessibleModal: React.FC<AccessibleModalProps> = ({ isOpen, onClose, title, children }) => {
  const modalRef = useRef<HTMLDivElement>(null);
  const previouslyFocusedElement = useRef<HTMLElement | null>(null);

  useEffect(() => {
    if (!isOpen) return;

    previouslyFocusedElement.current = document.activeElement as HTMLElement;

    const handleKeyDown = (event: KeyboardEvent) => {
      if (event.key === 'Escape') {
        onClose();
      } else if (event.key === 'Tab') {
        if (!modalRef.current) return;
        const focusableElements = modalRef.current.querySelectorAll<HTMLElement>(
          'button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])'
        );
        const firstElement = focusableElements[0];
        const lastElement = focusableElements[focusableElements.length - 1];

        if (event.shiftKey) {
          if (document.activeElement === firstElement) {
            lastElement?.focus();
            event.preventDefault();
          }
        } else {
          if (document.activeElement === lastElement) {
            firstElement?.focus();
            event.preventDefault();
          }
        }
      }
    };

    document.addEventListener('keydown', handleKeyDown);
    document.body.style.overflow = 'hidden';
    
    const timeoutId = setTimeout(() => modalRef.current?.focus(), 0);

    return () => {
      clearTimeout(timeoutId);
      document.removeEventListener('keydown', handleKeyDown);
      document.body.style.overflow = '';
      previouslyFocusedElement.current?.focus();
    };
  }, [isOpen, onClose]);

  if (!isOpen) return null;

  return ReactDOM.createPortal(
    <div
      className="modal-overlay"
      onClick={onClose}
      role="dialog"
      aria-modal="true"
      aria-labelledby="modal-title"
      ref={modalRef}
      tabIndex={-1}
    >
      <div className="modal-content" onClick={(e) => e.stopPropagation()}>
        <div className="modal-header">
          <h3 id="modal-title">{title}</h3>
          <button onClick={onClose} aria-label="Close modal">&times;</button>
        </div>
        <div className="modal-body">{children}</div>
      </div>
    </div>,
    document.body
  );
};

export default AccessibleModal;

Tooltips: The Lighter Sibling

Tooltips test a different set of skills: event handling and dynamic positioning. They are simpler than modals but have their own traps.

The core challenge is positioning. A robust tooltip uses JavaScript to calculate its position, not just CSS. Use the trigger element's getBoundingClientRect() to get its coordinates and size, then position the tooltip absolutely. This is the only way to handle viewport collision (e.g., a tooltip at the top of the screen should open downwards).

Another key detail is visibility delay. Use setTimeout on mouseenter to prevent the tooltip from flashing as the user's cursor moves across the screen. Use another small delay on mouseleave to allow the user to move their cursor from the trigger to the tooltip itself if it were interactive.

For accessibility, link the tooltip to its trigger with aria-describedby. This tells screen readers that the tooltip's content describes the trigger element.

Try it

Refactor the modal logic into a custom hook, useModal(). The hook should manage the isOpen state and encapsulate all the useEffect logic (focus trapping, scroll lock, keyboard events). This is a common pattern for abstracting complex component behavior and a great way to show you think about reusability.

Next: Drag & Drop Functionality (Basic)

Lock it in — apply this lesson under interview conditions.

Try a free mock interviewPractice machine coding problems
Previous

Pagination & Infinite Scroll

Next

Drag & Drop Functionality (Basic)