Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR TYPESCRIPT

click outside hook in react

import { useEffect } from 'react';

// Hook
function useOnClickOutside(ref, buttonRef, handler) {
  useEffect(
    () => {
      const listener = event => {
        // Do nothing if clicking ref's element or descendent elements
        if (!ref.current || ref.current.contains(event.target) || buttonRef.current.contains(event.target)) {
          return;
        }
        handler(event);
      };
      document.addEventListener('mousedown', listener);
      document.addEventListener('touchstart', listener);
      return () => {
        document.removeEventListener('mousedown', listener);
        document.removeEventListener('touchstart', listener);
      };
    },
    // Add ref and handler to effect dependencies
    // It's worth noting that because passed in handler is a new ...
    // ... function on every render that will cause this effect ...
    // ... callback/cleanup to run every render. It's not a big deal ...
    // ... but to optimize you can wrap handler in useCallback before ...
    // ... passing it into this hook.
    [ref, handler]
  );
}

export default useOnClickOutside;

//component/Header.tsx
const header = () => {
  const ref = useRef(null);
  const buttonRef = useRef(null);
  console.log(buttonRef);

  useOnClickOutside(ref, buttonRef, () => setIsOpen(false));
Source by usehooks.com #
 
PREVIOUS NEXT
Tagged: #click #hook #react
ADD COMMENT
Topic
Name
1+2 =