Skip to content

Instantly share code, notes, and snippets.

@lesleh
Created February 21, 2020 16:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lesleh/8c479ba9229fc1bebf2773e27e731574 to your computer and use it in GitHub Desktop.
Save lesleh/8c479ba9229fc1bebf2773e27e731574 to your computer and use it in GitHub Desktop.
import React from 'react';
import useWindowEvent from './useWindowEvent';
function Example() {
useWindowEvent('keydown', (e) => {
console.log('Pressed', e.key);
});
return <div>Example</div>;
}
import { useEffect } from 'react';
const useWindowEvent = (eventName, onEvent) => {
// Window check is isolated to here
if(typeof window === 'object') {
return;
}
useEffect(() => {
if (onEvent) {
window.addEventListener(eventName, onEvent, true);
}
return () => {
if (onEvent) {
window.removeEventListener(eventName, onEvent, true);
}
};
}, [eventName, onEvent]);
};
export default useWindowEvent;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment