Handles the event of clicking outside of the wrapped component.
ref
and a callback
to handle the click
event.useEffect()
hook to append and clean up the click
event.useRef()
hook to create a ref
for your click component and pass it to the useClickOutside
hook.const useClickOutside = (ref, callback) => {
const handleClick = e => {
if (ref.current && !ref.current.contains(e.target)) {
callback();
}
};
React.useEffect(() => {
document.addEventListener('click', handleClick);
return () => {
document.removeEventListener('click', handleClick);
};
});
};
const ClickBox = ({ onClickOutside }) => {
const clickRef = React.useRef();
useClickOutside(clickRef, onClickOutside);
return (
<div
className="click-box"
ref={clickRef}
style={{
border: '2px dashed orangered',
height: 200,
width: 400,
display: 'flex',
justifyContent: 'center',
alignItems: 'center'
}}
>
<p>Click out of this element</p>
</div>
);
};
ReactDOM.render(
<ClickBox onClickOutside={() => alert('click outside')} />,
document.getElementById('root')
);
React, Hooks
Handles the event of clicking inside the wrapped component.
React, Hooks
Handles the event of hovering over the wrapped component.
React, Hooks
Creates a portal, allowing rendering of children outside the parent component.