React Event Types in TypeScript

  1. Add Types to React Events in TypeScript
  2. Use React SyntheticEvent Type for Events in TypeScript
  3. Handle Keyboard Events in TypeScript
  4. Handle Mouse Events in TypeScript
React Event Types in TypeScript

In React, there is often a need to listen to event listeners triggered due to some actions on some HTML elements. TypeScript has strong typing support for all events triggered due to some actions such as touch, click, focus and others on HTML elements.

This article will demonstrate how to add types to different events in React.

Add Types to React Events in TypeScript

React has its type definitions for various HTML events triggered by actions on the DOM. The events are triggered due to some action, such as a click or change of some input element.

An example of an event trigger is the standard HTML text box.

<input value={value} onChange={handleValueChange} />

The above shows an example in jsx where handleValueChange receives an event object referring to the event triggered due to the change in the input in the text input box.

Considering an example of React code segment, a proper type has to be added for events passed to the handleValueChange function.

const InputComponent = () => {
    const [ value, setValue ] = React.useState<string>("");

    const handleValueChange :  React.ChangeEventHandler<HTMLInputElement> = (event) => {
        setValue(event.target.value);
    }

    return (
            <input value={value} onChange={handleValueChange}/>
    )
}

Thus the type ChangeEventHandler<HTMLInputElement> is the type for text change event in the input text box. It can be imported from React like import {ChangeEventHandler} from 'react'.

This type can also be represented by the type React.FormEvent<HTMLInputElement>. Some useful type aliases for React events can be:

type InputChangeEventHandler = React.ChangeEventHandler<HTMLInputElement>
type TextAreaChangeEventHandler = React.ChangeEventHandler<HTMLTextAreaElement>
type SelectChangeEventHandler = React.ChangeEventHandler<HTMLSelectElement>

// can be used as
const handleOptions : SelectChangeEventHandler = (event) => {

}

Use React SyntheticEvent Type for Events in TypeScript

The React SyntheticEvent type acts as a wrapper for all event types and can be used if strong type safety is not required. A type assertion can be used for some inputs as required.

const FormElement = () => {
    return (
        <form
        onSubmit={(e: React.SyntheticEvent) => {
            e.preventDefault();

            // type assertions done on the target
            const target = e.target as typeof e.target & {
                email: { value: string };
                password: { value: string };
            };
            const email = target.email.value;
            const password = target.password.value;

        }}
        >
            <div>
                <label>
                Email:
                <input type="email" name="email" />
                </label>
            </div>
            <div>
                <label>
                Password:
                <input type="password" name="password" />
                </label>
            </div>
            <div>
                <input type="submit" value="Sign in" />
            </div>
        </form>
    )
}

Handle Keyboard Events in TypeScript

Keyboard events are triggered when a key is pressed on the keyboard. React has great support for types regarding keyboard events.

const handleKeyBoardPress = (event : React.KeyboardEvent<Element>) => {
    if (event.key === 'Enter'){
        // do something on press of enter key
    }
}

It can also be represented as an Event Handler.

const handleKeyBoardPress : KeyboardEventHandler<Element> = (event) => {
    if (event.key === 'Enter'){
        // do something on press of enter key
    }
}

Element is the component in which the following function handleKeyBoardPress is wrapped.

Handle Mouse Events in TypeScript

Mouse Events can also be supported by adding types in TypeScript. Type assertions are required to access the methods associated with the HTML element though which the mouse event was triggered.

const handleOnClick : React.MouseEventHandler<HTMLInputElement> = (event) => {
    const HTMLButton = e.target as HTMLElement;
}
Shuvayan Ghosh Dastidar avatar Shuvayan Ghosh Dastidar avatar

Shuvayan is a professional software developer with an avid interest in all kinds of technology and programming languages. He loves all kinds of problem solving and writing about his experiences.

LinkedIn Website

Related Article - TypeScript React