use-detectoutside-click
v1.0.4
Published
a simple way to detect, if an element got click
Downloads
4
Maintainers
Readme
use-detectoutside-click
using use-detectoutside-click
Install
npm install use-detectoutside-click
Usage
- use useref to create element reference
- call the useDetectOutsideClick hooks and pass the ref name as parameter
- set a variable name to extract the condition of the output as you do with useState
import { useRef } from 'react';
import { useDetectOutsideClick } from 'use-detectoutside-click';
const Block = () =>{
const blockRef = useRef(null)
const blockRef2 = useRef(null)
const [blockOutsideClick] = useDetectOutsideClick(blockRef);
const [blockOutsideClick2] = useDetectOutsideClick(blockRef2);
return(
<>
<div className="blockContainer" ref={blockRef}>
<h1>I am heading {blockOutsideClick.toString()}</h1>
<p>Lorem ipsum some text over here will be display just read it carefully.</p>
<button type="button">Click to know more</button>
</div>
<div className="blockContainer" ref={blockRef2}>
<h1>I am heading2 {blockOutsideClick2.toString()}</h1>
<p>Lorem ipsum some text over here will be display just read it carefully.</p>
<button type="button">Click to know more</button>
</div>
</>
)
}
Output
In the above example will return true if someone click outside the targeted element.