Trigger Callback When Click Outside – react-cool-onclickoutside

Description:

A React hook library that triggers a callback when the user clicks outside of the target component(s) area.

Useful for dropdown menu, modal window, tooltip popup, etc.

Install & Import:

# Yarn
$ yarn add react-cool-onclickoutside

# NPM
$ npm i react-cool-onclickoutside –save

mport React, { useState } from “react”;
import useOnclickOutside from “react-cool-onclickoutside”;

Basic Usage:

const Dropdown = () => {
  const [openMenu, setOpenMenu] = useState(false);
  const ref = useOnclickOutside(() => {
    setOpenMenu(false);
  });
  const handleClickBtn = () => {
    setOpenMenu(!openMenu);
  };
  return (
    <div>
      <button onClick={handleClickBtn}>Button</button>
      {openMenu && <div ref={ref}>Menu</div>}
    </div>
  );
};

Preview:

Trigger Callback When Click Outside - react-cool-onclickoutside

Tags:

Add Comment