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
- Open the modal when the "Open Modal" button is clicked.
- Close the modal when the close button (X) is clicked.
- Close the modal when clicking outside of it.
- Prevent the modal from closing when clicking inside the modal content.
- Implement keyboard accessibility: close the modal when the Escape key is pressed.
Requirements
- The modal should be hidden by default.
- Clicking the "Open Modal" button should display the modal.
- Clicking the close button (X) should hide the modal.
- Clicking outside the modal content should close the modal.
- Clicking inside the modal content should not close the modal.
- Pressing the Escape key should close the modal.
- The modal should have a semi-transparent overlay covering the rest of the page when open.
- 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