H
H
hamster1410952021-03-23 16:52:55
React
hamster141095, 2021-03-23 16:52:55

What type to specify for event path in React?

In general, there is the usual handleClick to show and hide the menu if the click does not land on that menu. Can't describe type for event which includes path, MouseEvent doesn't pass....

const [isVisiblePopup, setIsVisiblePopup] = useState(false);
  const mobileButtonsRef = useRef(null);
  const isTrainer = userRole === 'trainer'
  const handleOutsideClick = (event: MouseEvent) => {
    const path = event.path || (event.composedPath && event.composedPath());
    if (path && !path.includes(mobileButtonsRef.current)) {
         setIsVisiblePopup(false);
    }
  };

  useEffect(() => {
    document.body.addEventListener('click', handleOutsideClick);
    return () => {
        document.body.removeEventListener('click', handleOutsideClick);
    };
  }, []);


Property 'path' does not exist on type 'MouseEvent'

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sun_Day, 2021-03-23
@Sun_Day

Probably it was not added there for some reason. There is a suspicion that it is precisely so that you do not use it.
It was not possible to find it in the mozilla, but it is in chrome. Of course, you can write a bypass type, but you probably shouldn't use this property if any kind of cross-browser compatibility is important.
But with the composedPath function, everything is in order.
https://developer.mozilla.org/en-US/docs/Web/API/E...
But if it's absolutely necessary, then something like this:

type M = MouseEvent & {
    path: Node[];
}
  const handleOutsideClick = (event: M ) =>

6059fcedca4bc829495530.jpeg
6059fcf7e1b25851798383.jpeg

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question