Advertisement
deedspool

useOutsideClick

Nov 30th, 2023
787
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import React, { useEffect } from 'react'
  2.  
  3. const useOutsideClick = (ref, callback) => {
  4.   const handleClick = e => {
  5.     if (ref.current && !ref.current.contains(e.target)) {
  6.       callback();
  7.     }
  8.   };
  9.  
  10.   useEffect(() => {
  11.     document.addEventListener("click", handleClick);
  12.  
  13.     return () => {
  14.       document.removeEventListener("click", handleClick);
  15.     };
  16.   });
  17. };
  18.  
  19. export default useOutsideClick;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement