How do I get the event type for mouseDown in React on a canvas?

748 Views Asked by At

I'm trying to use the <canvas /> element in react but struggling to create the event type for it. I have seen this article. I can get it work by importing that interface and having my function as below. However I still get typescript errors: Cannot find name "NativeMouseEvent" and "UIEvent" is not generic.

Just trying to create a mouse event handler something like this.

function myCanvas() {

  const handleMouseDown = (event: MouseEvent<HTMLCanvasElement>) => {
    {clientX, clientY} = event;
    console.log( clientX, clientY) 
  };

  return <canvas onMouseDown={handleMouseDown} />

}

Hoping for some explanations of how to find and use event types in React. It seems like there aren't a lot of good resources for something that seems like it would be pretty common place.

1

There are 1 best solutions below

0
Max On

Hi not sure from question what you're importing or not importing but if you use MouseEvent type from React the types should work. If you just type MouseEvent without importing it from React will reference regular event types such as interface MouseEvent extends Event { } , at least in React 16.

But you can do this

function myCanvas() {
    const handleMouseDown = (event: React.MouseEvent<HTMLElement>) => {
        const { clientX, clientY } = event;
    };

    return <canvas onMouseDown={handleMouseDown} />;
}

You should also capitalize myCanvas so you don't get JSX type errors. Best