From 6f929378f07be94208de3844c3b5da200074e698 Mon Sep 17 00:00:00 2001 From: Adam Coard Date: Tue, 29 Sep 2020 23:25:21 +0000 Subject: [PATCH] Close the profile password modal via 'Esc' key --- components/settings/ProfileSettings.js | 5 +++++ hooks/useEscapeKey.js | 19 +++++++++++++++++++ 2 files changed, 24 insertions(+) create mode 100644 hooks/useEscapeKey.js diff --git a/components/settings/ProfileSettings.js b/components/settings/ProfileSettings.js index e23c73ed..6fe18d19 100644 --- a/components/settings/ProfileSettings.js +++ b/components/settings/ProfileSettings.js @@ -10,6 +10,7 @@ import TimezoneSetting from 'components/settings/TimezoneSetting'; import Dots from 'assets/ellipsis-h.svg'; import styles from './ProfileSettings.module.css'; import DateRangeSetting from './DateRangeSetting'; +import useEscapeKey from 'hooks/useEscapeKey'; export default function ProfileSettings() { const user = useSelector(state => state.user); @@ -22,6 +23,10 @@ export default function ProfileSettings() { setMessage(); } + useEscapeKey(() => { + setChangePassword(false); + }); + return ( <> diff --git a/hooks/useEscapeKey.js b/hooks/useEscapeKey.js new file mode 100644 index 00000000..b8020c31 --- /dev/null +++ b/hooks/useEscapeKey.js @@ -0,0 +1,19 @@ +import { useEffect, useCallback } from 'react'; + +export default function useEscapeKey(handler) { + const escFunction = useCallback(event => { + if (event.keyCode === 27) { + handler(event); + } + }, []); + + useEffect(() => { + document.addEventListener('keydown', escFunction, false); + + return () => { + document.removeEventListener('keydown', escFunction, false); + }; + }, [escFunction]); + + return null; +}