Explain Codes LogoExplain Codes Logo

Typescript: React event types

javascript
event-handling
typescript
react
Nikita BarsukovbyNikita Barsukov·Mar 8, 2025
TLDR

Harness the true power of TypeScript by utilizing accurate React event types such as React.MouseEvent. By assigning these to particular elements, in this case <button>, you ensure the strong typing benefits of TypeScript are at your disposal. Here's a sneak peek:

const handleClick = (event: React.MouseEvent<HTMLButtonElement>) => { // Click response logic (or lack thereof) goes here! }; <button onClick={handleClick}>Click me... if you dare</button>

Highlighting the <HTMLButtonElement> as it performs a key role in curating the event type for your event handlers.

Leveraging event types in TypeScript

TypeScript gives us the opportunity to embrace typed event handlers - a real shot in the arm for maintaining high-quality code and guaranteeing expected outcomes for your React components.

Taming the ChangeEvent

When handling elements such as <input>, opt for React.ChangeEvent<HTMLInputElement>. Allowing TypeScript to correlate the correct properties such as value and onChange, is like asking your GPS for directions!

const handleChange = (event: React.ChangeEvent<HTMLInputElement>) => { const { name, value } = event.target; // Perfect catch! // Command control of the input change };

Mastering mouse events

When dealing with mouse events on buttons, React.MouseEvent<HTMLButtonElement> opens the door to mouse-influenced properties such as clientX and clientY, offering a rich palette of information about the event.

Keyboard events - Your type, literally!

For keyboard interactions, React.KeyboardEvent is your trusted companion. With it, keys pressed are under your command providing more granular control over user interaction.

The dreaded 'any' - not on my watch!

Abstain from the any type for event parameters. It's the kryptonite for TypeScript's static typing superpowers, and introduces gremlins in the form of tricky-hard-to-debug errors.

Advanced event handling - Level up!

With the basics covered, let’s roll up our sleeves and tackle more complex scenarios.

Event targets - I choose you, Pikachu!

Cast the event target when there's a need to access properties that are element-specific. This becomes a necessity when a generic event handler is employed across different element types.

const handleEvent = (event: React.SyntheticEvent) => { const target = event.target as HTMLInputElement; // Casting spell, poof! const value = target.value; // Introduce complex event handling logic here };

The specificity of event types

When setting up form update handlers, prefer event.currentTarget for accessing form elements. This ensures the right form is being updated especially in those pesky cases when multiple forms are involved.

const updateField = (event: React.ChangeEvent<HTMLInputElement>) => { this.setState({ [event.currentTarget.name]: event.currentTarget.value }); // Strings are everything! };

Every event has its target

The formidable SyntheticEvent<T> interface is indeed generic and can take a type parameter corresponding to the DOM element associated with the event. This is detective-level type-checking!

const handleGenericEvent = <T extends HTMLElement>(event: React.SyntheticEvent<T>) => { // Is it a bird? Is it a plane? It's properties specific to T! };

Deep dive into React event types

Pursuing more than surface knowledge is essential for mastering React event types provided by TypeScript.

The Source of All Wisdom

The sacred texts comprising the TypeScript definition files (lib.dom.d.ts) and the temple of React documentation are fertile grounds filled with knowledge about event types. Scan through these to discover the cornucopia of properties and events available.

The Intersection Paradigm

By acknowledging that currentTarget is an intersecting point between the generic type constraint and EventTarget, you're one step closer to mastering TypeScript and React.

Form event handling - What to choose?

Contrary to popular belief, opt for React.ChangeEvent overReact.FormEvent for handling input modifications. However, React.FormEvent<EventTarget> is the designated handler for form submissions, ensuring your form handling skills are top-tier.