0

I'm listening to click bubbled events on window and I want to check if the click occurred within a a specific element in order to dispatch (or not) an action. The inerestinc part of my component is the following one:

const handleClickOutsideSearchArea = (event: Event) => { if (!textAreaRef?.current?.contains(event.target)) { dispatch({type: <MY-ACTION>}); } }; window.addEventListener('click', handleClickOutsideSearchArea); 

this code works, BUT event.target is an EventTarget whether contains needs a Node, a child of EventTarget, then Flow complaints about it.

How could I fix this? Is there a way to get the node from the event?

3
  • textAreaRef.current already references the correspondent DOM's node, use it instead of target (Also take a look at event delegation in React) Commented Nov 12, 2020 at 13:21
  • the problem is that I'm listening on window. I'll update the question in order to give it a better context Commented Nov 12, 2020 at 13:25
  • event delegation is not in order in this case, because I need to listen to the whole DOM, not the react elements. Imagine a react app within a page with other elements for instance Commented Nov 12, 2020 at 13:26

1 Answer 1

1

The problem is that EventTraget might contain either an instance of an Element, Document or Window where the latter doesn't have a contains method.

You can tackle it by checking that your EventTarget isn't window and casting your type to Element, i.e (!textAreaRef?.current?.contains(event.target as Element)) { ...

With some aesthetics added, this could look something like:

const { target } = event; if(target !== window) { // or !!target.contains to check for the presence of the method const containsTarget = textAreaRef?.current?.contains(target as Element); if(containsTarget) { dispatch({type: <MY-ACTION>}); } } 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.