Docs
Click Away

Click Away

Detect clicks outside of specific component.

About

The useClickAway hook is a handy tool for detecting clicks outside a designated component. It enables you to provide a callback function that activates whenever a click happens outside the component's boundaries. This hook is especially useful for implementing dropdown menus, modals, or other UI elements that should close when a user clicks outside of them. By attaching event listeners to the document, the hook determines if the click target is within the component's reference, and if not, it calls the specified callback function.

Parameters

NameTypeDescription
callbackfunctionThe callback function that is provided as an argument to useClickAway. This function is invoked whenever a click event is detected outside of the referenced element. The event object from the click is passed to this callback function.

Return Values

NameTypeDescription
refReact refThis is a ref object returned by the hook. It should be attached to a React element to monitor click events. The ref provides a way to access the properties of the element it is attached to.

Installation

Run the following command:

npx scriptkavi-hooks@latest add click-away

Usage

import { useClickAway } from "@/hooks/click-away"
import * as React from "react"
 
import { closeIcon } from "./icons"
 
export default function App() {
  const [isOpen, setIsOpen] = React.useState(false)
  const ref = useClickAway(() => {
    setIsOpen(false)
  })
 
  const handleOpenModal = () => {
    if (isOpen === false) {
      setIsOpen(true)
    }
  }
 
  return (
    <>
      <section>
        <h1>useClickAway</h1>
        <button className="link" onClick={handleOpenModal}>
          Open Modal
        </button>
      </section>
      {isOpen && (
        <dialog ref={ref}>
          <button onClick={() => setIsOpen(false)}>{closeIcon}</button>
          <h2>Modal</h2>
          <p>
            Click outside the modal to close (or use the button) whatever you
            prefer.
          </p>
        </dialog>
      )}
    </>
  )
}