React hook useClickAway()
that reacts to clicks outside the bound element, and calls the expression that is passed in when this event is detected.
Suppose you're working on a Modal component that renders a dialog box, and you wish to close the modal if the user clicks away this is the ideal scenario for useClickAway()
custom hook.
Using npm
:
npm i use-click-away --save
Import the hook:
import { useClickAway } from "use-click-away";
export default () => {
const [modal, setModal] = React.useState(false);
const clickRef = React.useRef("");
useClickAway(clickRef, () => {
setModal(false);
});
return (
<div className="container">
<button onClick={() => setModal(true)}>Show Property</button>
{modal && <Modal
modal={modal}
setModal={setModal}
onClickOutside={onClickOutside}
/>}
</div>
);
};
clickRef: element
- The dom element to bind our hook.callback: function
- The callback that runs after user click
- React - A JavaScript library for building user interfaces
MIT Licensed. Copyright (c) George Bardi 2020.