React Modal Component
npm install react-modal_by_cl
import React, { useState } from 'react';
import Modal from './Modal';
import './style.css';
const App = () => {
const [isModalOpen, setIsModalOpen] = useState(false);
return (
setIsModalOpen(false)}>
Modal Content
This is an example of modal content.
);
};
export default App;
`
$3
`
isOpen={isModalOpen}
onClose={() => setIsModalOpen(false)}
overlayClassName="customOverlay"
modalClassName="customModal"
buttonClassName="customCloseButton"
>
Custom Styled Modal
`
Accessibility
1. Keyboard Navigation:
- Press Escape to close the modal
- Use Tab and Shift + Tab to navigate within the modal content.
2. ARIA Attributes:
- role="dialog" and aria-modal="true" are used to ensure compatibility with screen readers.
Key Functions
handleKeyDown
Handles keyboard interactions, including:
- Closing the modal with the Escape key.
- Managing focus trapping with the Tab key.
trapFocus
Ensures focus remains within the modal by cycling through focusable elements.
handleOverlayClick
Closes the modal if a click occurs on the overlay (background).
Styling
The component is fully customizable through CSS class names provided via props.
$3
`
overlay: {
position: 'fixed',
top: 0,
left: 0,
width: '100%',
height: '100%',
backgroundColor: 'rgba(0, 0, 0, 0.5)',
display: 'flex',
justifyContent: 'center',
alignItems: 'center',
zIndex: 1000,
},
modal: {
position: 'relative',
},
closeButton: {
position: 'absolute',
top: '-10px',
right: '-10px',
borderRadius: '100%',
border: 'none',
cursor: 'pointer',
},
`
$3
`
.modal {
background-color: #fff;
border-radius: 5px;
box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
text-align: center;
padding: 20px;
}
.closeButton {
background: black;
color: white;
font-size: 20px;
}
`
$3
Use the overlayClassName, modalClassName, and buttonClassName props to apply your custom styles.
Best Practices
1. Provide Required Props:
- Ensure isOpen and onClose are passed to control modal behavior properly.
2. Test Focus Management:
- Verify focus trapping with Tab navigation in various scenarios.
3. Customize Styles:
- Match the modal's appearance to your application's theme using the class name props.
4. Ensure Accessibility:
- Validate ARIA attributes and focus trapping for assistive technologies.
Troubleshooting
1. Modal Not Closing on Escape Key
- Verify onClose is passed and correctly implemented
2. Focus Not Trapped:
- Check that all focusable elements inside the modal are correctly defined.
3. Overlay Click Not Working:
- Ensure handleOverlayClick is triggered by checking event propagation.
Notes
- Manage the isOpen` state in the parent component to avoid unintended behavior.