diff --git a/app/soapbox/components/modal_root.tsx b/app/soapbox/components/modal_root.tsx index eabd450d0..f34597d5b 100644 --- a/app/soapbox/components/modal_root.tsx +++ b/app/soapbox/components/modal_root.tsx @@ -47,12 +47,13 @@ const ModalRoot: React.FC = ({ children, onCancel, onClose, type }) const isEditing = useAppSelector(state => state.compose.get('compose-modal')?.id !== null); - const handleKeyUp = useCallback((e) => { - if ((e.key === 'Escape' || e.key === 'Esc' || e.keyCode === 27) - && !!children) { + const visible = !!children; + + const handleKeyUp = (e: KeyboardEvent) => { + if (e.key === 'Escape' || e.key === 'Esc' || e.keyCode === 27) { handleOnClose(); } - }, []); + }; const handleOnClose = () => { dispatch((_, getState) => { @@ -136,6 +137,8 @@ const ModalRoot: React.FC = ({ children, onCancel, onClose, type }) }; useEffect(() => { + if (!visible) return; + window.addEventListener('keyup', handleKeyUp, false); window.addEventListener('keydown', handleKeyDown, false); @@ -143,7 +146,7 @@ const ModalRoot: React.FC = ({ children, onCancel, onClose, type }) window.removeEventListener('keyup', handleKeyUp); window.removeEventListener('keydown', handleKeyDown); }; - }, []); + }, [visible]); useEffect(() => { if (!!children && !prevChildren) { @@ -172,8 +175,6 @@ const ModalRoot: React.FC = ({ children, onCancel, onClose, type }) } }); - const visible = !!children; - if (!visible) { return (