Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I type an event with mouseEvent and event.target (react project with typescript)?

I need your help for my project.
I want to close a menu when I click outside.
I write the following code but I have problems with typescript.

The code works when I use any to type the "ev" argument but I know it's not recommanded.

Here my code :

  useEffect(() => {
    const checkIfClickedOutside = (ev: any) => {
      if (isMenuOpen && menuRef.current && !menuRef.current?.contains(ev.target)) {
        setIsMenuOpen(false);
      }
    };
    document.addEventListener('mousedown', checkIfClickedOutside);

    return () => {
      document.removeEventListener('mousedown', checkIfClickedOutside);
    };
  }, [isMenuOpen, menuRef]);

I try with MouseEvent but I have this error :

Argument of type 'EventTarget' is not assignable to parameter of type 'Node'.
Type 'EventTarget' is missing the following properties from type 'Node': baseURI, childNodes, firstChild, isConnected, and 43 more. 

and this :

const checkIfClickedOutside: (ev: MouseEvent) => void
No overload matches this call.
  Overload 1 of 2, '(type: "mousedown", listener: (this: Document, ev: MouseEvent) => any, options?: boolean | AddEventListenerOptions | undefined): void', gave the following error.
    Argument of type '(ev: MouseEvent) => void' is not assignable to parameter of type '(this: Document, ev: MouseEvent) => any'.
      Types of parameters 'ev' and 'ev' are incompatible.
        Type 'MouseEvent' is missing the following properties from type 'MouseEvent<Element, MouseEvent>': nativeEvent, isDefaultPrevented, isPropagationStopped, persist
  Overload 2 of 2, '(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions | undefined): void', gave the following error.
    Argument of type '(ev: MouseEvent) => void' is not assignable to parameter of type 'EventListenerOrEventListenerObject'.
      Type '(ev: MouseEvent) => void' is not assignable to type 'EventListener'.
        Types of parameters 'ev' and 'evt' are incompatible.
          Type 'Event' is missing the following properties from type 'MouseEvent<Element, MouseEvent>': altKey, button, buttons, clientX, and 18 more

Can someone help me? Thanks a lot !

like image 718
Carmen Avatar asked Feb 01 '26 14:02

Carmen


1 Answers

If you use MouseEvent from

 import {MouseEvent} from "react"

you get that error. Instead, do not import MouseEvent. Use the globally available MouseEvent

like image 147
Yilmaz Avatar answered Feb 04 '26 05:02

Yilmaz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!