Nice. Do you have it as open source repo or a gist or a codesandbox?
Well, here it is.
import { useEffect } from 'react'; export default function useClickAway(onClickAway, ref) { useEffect(() => { document.addEventListener('mousedown', handleClick); return () => { document.removeEventListener('mousedown', handleClick); }; }, []); function handleClick(event) { if (ref.current && !ref.current.contains(event.target)) onClickAway(); } }
This is what I did before in the component and how it's now:
componentDidMount() { document.addEventListener('mousedown', this.handleClickOutside); } componentWillUnmount() { document.removeEventListener('mousedown', this.handleClickOutside); } setWrapperRef = node => { this.wrapperRef = node; }; handleClickOutside = event => { if (this.wrapperRef && !this.wrapperRef.contains(event.target)) { this.props.onClickAway(); } };
vs
const wrapperRef = useRef(); useClickAway(props.onClickAway, wrapperRef);
Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment's permalink.
Hide child comments as well
Confirm
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
Nice. Do you have it as open source repo or a gist or a codesandbox?
Well, here it is.
This is what I did before in the component and how it's now:
vs