0.0.2 • Published 7 years ago
on-outside-click-hook v0.0.2
on-outside-click-hook
A React custom hook to detect clicks which triggers outside the element and then fire an event.
Make sure your
reactandreact-domversion is16.8.1or higher. Internallyon-outside-click-hookuses react hooks which is only supported after version16.8.1ofreact
How to install
$ yarn add on-outside-click-hookUsage
import useOnOutsideClick from 'on-outside-click-hook'
const CustomComponent = () => {
const elementInstance = useOnOutsideClick(() => alert('hello'))
return <div ref={elementInstance}>
<h1>Hello</h1>
</div>
} useOnOutsideClick(func:function)
Fires passed function when click event triggers outside the target element
When we will use useOnOutsideClick in our functional components we have to pass it a function which will be called when click event triggers outside the target element. for e.g useOnOutsideClick(() => alert('hello'))
Also note when we call useOnOutsideClick it returns an elementInstance which is basically a ref which will be passed to the target element as a ref. This is how useOnOutsideClick tracks when the click event happens outside the element.
import useOnOutsideClick from 'on-outside-click-hook'
const CustomComponent = () => {
const elementInstance = useOnOutsideClick(() => alert('hello'))
// elementInstance will be passed to div as a ref
return <div ref={elementInstance}>
<h1>Hello</h1>
</div>
}