trainReact.com
||

1. React Modal Functionality

Medium
Category: Component Patterns
useStateuseEffectuseRefState ManagementEvent Handlers

Problem Description

In this challenge, you'll be implementing a functional modal component in React. You're provided with a basic modal structure and a button to open it. Your task is to add the necessary functionality to make the modal interactive and user-friendly.

What You Need to Implement

  1. Open the modal when the "Open Modal" button is clicked.
  2. Close the modal when the close button (X) is clicked.
  3. Close the modal when clicking outside of it.
  4. Prevent the modal from closing when clicking inside the modal content.
  5. Implement keyboard accessibility: close the modal when the Escape key is pressed.

Requirements

  1. The modal should be hidden by default.
  2. Clicking the "Open Modal" button should display the modal.
  3. Clicking the close button (X) should hide the modal.
  4. Clicking outside the modal content should close the modal.
  5. Clicking inside the modal content should not close the modal.
  6. Pressing the Escape key should close the modal.
  7. The modal should have a semi-transparent overlay covering the rest of the page when open.
  8. Implement proper accessibility attributes (aria-modal, aria-hidden, etc.).

Guidance

  • Use React state to manage the visibility of the modal.
  • Implement event listeners for click and keyboard events.
  • Use event propagation to handle clicks inside and outside the modal.
  • Consider using useEffect for adding and removing event listeners.
  • Implement focus management for better accessibility.

Constraints

  • Do not use any external modal libraries.
  • Stick to functional components and hooks.
  • Maintain the existing structure of the Modal component.

Error Handling

  • Ensure that event listeners are properly removed when the component unmounts.
  • Handle cases where the modal might be programmatically closed (e.g., by a parent component).

Example Usage

1<div>
2  <button onClick={openModal}>Open Modal</button>
3  <Modal isOpen={isModalOpen} onClose={closeModal}>
4    <h2>Modal Title</h2>
5    <p>This is the modal content.</p>
6  </Modal>
7</div>
8
// App.js
import React from 'react';
import Modal from './Modal';
import './styles.css';

function App() {
  // TODO: Implement state for modal visibility

  // TODO: Implement openModal function

  // TODO: Implement closeModal function

  return (
    <div className="App">
      <h1>React Modal Challenge</h1>
      <button onClick={null}>Open Modal</button>
      <Modal isOpen={null} onClose={null}>
        <h2>Modal Title</h2>
        <p>This is the modal content.</p>
      </Modal>
    </div>
  );
}

export default App;

Open browser consoleTests