Skip to main content

useClickOutside()

The useClickOutside() hook lets you trigger a callback whenever the user clicks outside of a target element

Import

import { useClickOutside } from 'react-haiku';

Usage

Clicked Outside 0 Times!
import { useState, useRef } from 'react'
import { useClickOutside } from "react-haiku"

export const Component = () => {
const [count, setCount] = useState(0);
const ref = useRef(null)

const handleClickOutside = () => setCount(count + 1);

useClickOutside(ref, handleClickOutside);

return (
<>
<b>Clicked Outside {count} Times!</b>
<button ref={ref}>Click Outside Of Me!</button>
</>
);
}

API

This hook accepts the following arguments:

  • ref - the target element, clicking outside of this element will trigger the handler
  • handler - the handler for what happens when you click outside of the target