Skip to content

Commit

Permalink
Dialog close via ESC
Browse files Browse the repository at this point in the history
  • Loading branch information
leegee committed Jul 5, 2024
1 parent 3eed62d commit 4c4918c
Showing 1 changed file with 14 additions and 1 deletion.
15 changes: 14 additions & 1 deletion src/components/Dialog.jsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
/* Dialog.jsx */
// components/Dialog.js
import { useRef } from 'react';
import { useEffect, useRef } from 'react';
import PropTypes from 'prop-types';
import styles from './Dialog.module.css';

Expand All @@ -13,6 +13,19 @@ export default function Dialog ( { isOpen, onClose, children } ) {
dialogRef.current.close();
}

useEffect( () => {
if ( isOpen && dialogRef.current ) {
const dialogRefCurrent = dialogRef.current;
const onCancel = () => {
console.log( 'Dialog canceled (ESC key pressed or outside click)' );
onClose();
};

dialogRefCurrent.addEventListener( 'cancel', onCancel );
return () => dialogRefCurrent.removeEventListener( 'cancel', onCancel );
}
}, [ dialogRef, isOpen, onClose ] );

return (
<dialog ref={ dialogRef } className={ styles.dialog }>
<button className={ styles.close } onClick={ onClose } title='Close'>×</button>
Expand Down

0 comments on commit 4c4918c

Please sign in to comment.