Trigger Callback When Click Outside – react-cool-onclickoutside

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

Download Details:

Author: wellyshen

Live Demo: View The Demo

Download Link: Download The Source Code

Official Website: https://github.com/wellyshen/react-cool-onclickoutside

License: MIT

You Might Be Interested In:

Tags:

Add Comment