Modal.tsx 983 B

123456789101112131415161718192021222324252627282930313233343536373839
  1. import Icon from '@/components/Icon';
  2. import { useCallback, useEffect, useState } from 'react';
  3. export function Modal({ children }) {
  4. const [isOpen, setIsOpen] = useState(false);
  5. const handleEscape = useCallback(e => {
  6. if (e.keyCode === 27) {
  7. setIsOpen(false);
  8. }
  9. }, []);
  10. useEffect(() => {
  11. if (isOpen) {
  12. document.addEventListener('keydown', handleEscape, false);
  13. }
  14. return () => {
  15. document.removeEventListener('keydown', handleEscape, false);
  16. };
  17. });
  18. const hideModal = e => {
  19. setIsOpen(false);
  20. };
  21. return isOpen ? (
  22. <div className="modal-backdrop" tabIndex={-1} role="dialog" onClick={hideModal} onKeyDown={hideModal}>
  23. <div className="modal">
  24. <a href="#" className="modal-close" data-dismiss="modal" aria-label="Close modal" onClick={hideModal}>
  25. <Icon name="x" />
  26. </a>
  27. <div className="modal-body">{children}</div>
  28. </div>
  29. </div>
  30. ) : null;
  31. }
  32. export default Modal;