useOnClickOutside

React hook for detecting clicks outside of a component.

Installation

npm install @mvdlei/hooks

Example

Usage

import React, { useRef } from "react";
import { useOnClickOutside } from "@mvdlei/hooks";
 
const MyComponent = () => {
  const myRef = useRef(null);
 
  useOnClickOutside(myRef, (event) => {
    console.log("Clicked outside the component!");
  });
 
  return <div ref={myRef}>My Component</div>;
};

Reference

useOnClickOutside<T extends HTMLElement = HTMLElement>(
  ref: React.RefObject<T>,
  handler: (event: MouseEvent) => void,
  mouseEvent: "mousedown" | "mouseup" = "mousedown",
): void;

Parameters

  • ref: Ref of the component.
  • handler: Handler to be called when a click outside occurs.
  • mouseEvent: Mouse event to listen to, defaults to "mousedown".

use-on-click-outside.ts