L
L
lookingfor22020-09-28 15:19:52
React
lookingfor2, 2020-09-28 15:19:52

How to track a click outside of a component?

I have a functional style component, how can I track a click outside of the component?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
0
0xD34F, 2020-09-28
@lookingfor2

const rootEl = useRef(null);

useEffect(() => {
  const onClick = e => rootEl.current.contains(e.target) || console.log('клик вне компонента');
  document.addEventListener('click', onClick);
  return () => document.removeEventListener('click', onClick);
}, []);

return (
  <div ref={rootEl}>
    ...
  </div>
);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question