Answers for "detect click outside element react typescript"

1

detect click outside element react typescript

function useOnClickOutside<T extends HTMLElement = HTMLElement>(
  ref: RefObject<T>,
  handler: (event: MouseEvent) => void
): void {
  useEffect(() => {
    const listener = (event: MouseEvent) => {
      const el = ref?.current;

      // Do nothing if clicking ref's element or descendent elements
      if (!el || el.contains(event.target as Node)) {
        return;
      }

      handler(event);
    };

    document.addEventListener(`mousedown`, listener);

    return () => {
      document.removeEventListener(`mousedown`, listener);
    };

    // Reload only if ref or handler changes
  }, [ref, handler]);
}

// Usage example, code below will not work if you just copy and paste


const MyComponent = (): JSX.Element => {
  const [show, setShow] = useState(false);

  const ref = useRef(null);

  const handleClickOutside = () => {
    // Your custom logic here
    console.log("clicked outside");
  };

  useOnClickOutside(ref, handleClickOutside);

  return (
    <>
      <button
        onClick={() => {
          setShow(!show);
        }}
      >
        Columns
      </button>
      {show ? (
        <section ref={ref} 
          <OtherComponentThatYouWantToShow />
        </section>
      ) : (
        <></>
      )}
    </>
  );
};
Posted by: Guest on September-16-2021
1

Detect click outside React component

import React, { useRef, useEffect } from "react";

/**
 * Hook that alerts clicks outside of the passed ref
 */
function useOutsideAlerter(ref) {
    useEffect(() => {
        /**
         * Alert if clicked on outside of element
         */
        function handleClickOutside(event) {
            if (ref.current && !ref.current.contains(event.target)) {
                alert("You clicked outside of me!");
            }
        }

        // Bind the event listener
        document.addEventListener("mousedown", handleClickOutside);
        return () => {
            // Unbind the event listener on clean up
            document.removeEventListener("mousedown", handleClickOutside);
        };
    }, [ref]);
}

/**
 * Component that alerts if you click outside of it
 */
export default function OutsideAlerter(props) {
    const wrapperRef = useRef(null);
    useOutsideAlerter(wrapperRef);

    return <div ref={wrapperRef}>{props.children}</div>;
}
Posted by: Guest on May-13-2021

Code answers related to "detect click outside element react typescript"

Code answers related to "TypeScript"

Browse Popular Code Answers by Language