How to Handle Mouse Events in React TypeScript Application

When dealing with user interactions, you often need to handle some user events like mouse clicks, keyboard input, etc.

Basic Handling#

To handle mouse event in React you can use MouseEvent type to declare types on handler event argument:

More Restrictive Handling#

You can specify the element on which an event is being handled. It improves the type-safety and shrinks possible properties and methods to those that apply to a given element.

Union as a Type Parameter#

If you want to create a handler that will handle events on buttons, links, and other elements, you can always use unions:

Extending Events#

If you need to create your own event with additional fields you can extend it from MouseEvent:

And then use it as a type parameter of handled event.

Sources#