31 - Modal Window for Alerts and Confirmations
Description
Create a reusable React component that displays modal windows for alerts and confirmations.
Features:
Displays messages and optional buttons for actions.
Overlays the main content to focus user attention.
Can be triggered from various parts of the application.
Handles user interactions (e.g., button clicks) to close the modal or confirm actions.
Constraints:
Ensure accessibility for users with assistive technologies.
Consider responsiveness for different screen sizes.
Puzzle Algorithm
Component Structure:
Define a functional component named
ModalWindow
.Accept props for:
isOpen
: Boolean to control modal visibility.title
: Text for the modal header (optional).message
: Content for the modal body.buttons
: Array of objects defining buttons (text and onClick handler).
Manage internal state for button clicks or other interactions.
JSX Rendering:
Render a container element (e.g.,
div
) with appropriate styling for:Modal overlay (to block background interaction).
Modal content (header, body, buttons).
Conditionally render the modal based on the
isOpen
prop.
Handling User Interactions:
Implement event handlers to close the modal or perform actions based on button clicks.
Update internal state or trigger callbacks as needed.
Accessibility:
Use ARIA attributes to describe the modal's role and structure for screen readers.
Ensure proper focus management when opening and closing the modal.
Code
Explanation
Props:
isOpen
: Determines whether the modal is displayed.title
: Optional header text for the modal.message
: Content displayed in the modal body.buttons
: Array of objects defining button properties (text and optional onClick handler).onClose
: Callback function triggered when the modal closes.
State Management:
confirmed
: Tracks whether a confirmation button was clicked (optional, useful for confirmations).
Event Handling:
handleClose
: Closes the modal and triggers theonClose
callback with theconfirmed
state (if applicable).handleButtonClick
: Handles individual button clicks, executing the button'sonClick
handler and updating theconfirmed
state for confirmation buttons.
Conditional Rendering:
The modal only renders if the
isOpen
prop is true.
Accessibility:
ARIA attributes can be added to the modal and its elements for better screen reader support.
Additional Notes
This code provides a basic structure for alerts and confirmations. You can customize it further to include features like styling, animations, and additional button types.
Consider integrating the modal with a state management library for more complex workflows.
Last updated