useClickAway
Execute a function when the user clicks outside a target element.
Parameters
- a click event callback funtion.
- and some options:
Name | Type | Description |
---|---|---|
ref | RefObject | the target element reference. |
Return Values
a ref
object of the target element.
TIP
If you want to cancel the click away function, just use stopPropagation method of the click event:
ts
const handleClick = (event) => {
event.stopPropagation();
...
}
const handleClick = (event) => {
event.stopPropagation();
...
}
Example Usage
tsx
import { useClickAway } from 'react-pre-hooks';
export default function Example() {
const ref = useClickAway(() => ref.current.classList.add('hide'));
const showModal = e => {
e.stopPropagation(); // cancel the click away function
ref.current.classList.remove('hide');
};
return (
<main>
<button onClick={showModal}>Open</button>
<div id="modal" ref={ref} className="hide">
<strong>Click Outside!</strong>
<p>to close this modal.</p>
</div>
</main>
);
}
import { useClickAway } from 'react-pre-hooks';
export default function Example() {
const ref = useClickAway(() => ref.current.classList.add('hide'));
const showModal = e => {
e.stopPropagation(); // cancel the click away function
ref.current.classList.remove('hide');
};
return (
<main>
<button onClick={showModal}>Open</button>
<div id="modal" ref={ref} className="hide">
<strong>Click Outside!</strong>
<p>to close this modal.</p>
</div>
</main>
);
}