Last active
April 20, 2023 11:46
-
-
Save JoaoTMDias/b5aeb6e02be7e6d25d5fd7f10826fc8a to your computer and use it in GitHub Desktop.
React hook to use as addEventListener in React's functional components
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { useEffect } from "react"; | |
/** | |
* This replaces the need for using window.addEventListener() when using react hooks. | |
* You use it in exactly the same way as window.addEventListener(). | |
* | |
* @example | |
* useEvent(event, listener, useCapture) | |
* | |
* @export | |
* @template T | |
* @param {EventHandler<T>} event | |
* @param {(this: Window, ev: WindowEventMap[T]) => any} listener | |
* @param {boolean} [passive=false] | |
*/ | |
export default function useEvent<T extends keyof WindowEventMap>( | |
event: T, | |
listener: (this: Window, ev: WindowEventMap[T]) => any, | |
passive = false, | |
) { | |
useEffect(() => { | |
// initiate the event handler | |
window.addEventListener(event, listener, passive); | |
// this will clean up the event every time the component is re-rendered | |
return function cleanup() { | |
window.removeEventListener(event, listener); | |
}; | |
}, []); | |
} |
working is fine only desktop view not working mobile view
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
yeh that's how i dealt with it