JIYIK CN >

Current Location:Home > Learning > PROGRAM > TypeScript >

React event types in TypeScript

Author:JIYIK Last Updated:2025/04/15 Views:

In React, you often need to listen to event listeners that are triggered due to certain operations on certain HTML elements. TypeScript has strong typing support for all events triggered due to certain operations on HTML elements, such as touch, click, focus, and other operations.

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

Adding types to React events in TypeScript

React has types for various HTML events that are triggered by operations on the DOM. Events are triggered as a result of some operation, such as clicking or changing some input element.

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

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

jsxAn example of this is shown above , where handleValueChangereceives a eventobject that references events that are triggered due to changes in the input in the text input box.

Considering the example of the React snippet, handleValueChangethe appropriate type must be added to the event passed to the 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}/>
    )
}

So the type ChangeEventHandler<HTMLInputElement>is the type of the text changed event in the input text box. It can be imported from React, for example import {ChangeEventHandler} from 'react'.

This type can also React.FormEvent<HTMLInputElement>be expressed using the type. 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) => {

}

SyntheticEventUsing React types for events in TypeScript

React SyntheticEventtypes act as a wrapper around all event types and can be used if strong type safety is not required. Type assertions can be used for certain inputs as needed.

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>
    )
}

Handling keyboard events in TypeScript

Keyboard events are fired when a key is pressed on the keyboard. React has good support for typing 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
    }
}

ElementIt is a component that encapsulates the following functions handleKeyBoardPress.

Handling mouse events in TypeScript

Mouse events can also be supported by adding types in TypeScript. Type assertions are required to access methods associated with the HTML element that triggers the mouse event.

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

For reprinting, please send an email to 1244347461@qq.com for approval. After obtaining the author's consent, kindly include the source as a link.

Article URL:

Related Articles

Handling exceptions with try..catch..finally in TypeScript

Publish Date:2025/04/15 Views:170 Category:TypeScript

This article will discuss try..catch..finally handling exceptions in TypeScript using the statement. Handling exceptions in TypeScript In TypeScript, try..catch..finally a block handles exceptions that occur during program runtime. It allow

Convert JSON object to a class in TypeScript

Publish Date:2025/04/15 Views:80 Category:TypeScript

Data on the internet flows in the form of strings, which can be converted into a very popular format called JSON. The JSON representation of this data usually represents an object or even a class in TypeScript. TypeScript provides the abili

Update TypeScript to the latest version using NPM

Publish Date:2025/04/15 Views:119 Category:TypeScript

This article provides a guide to update to the latest version of TypeScript using npm, which is the best and most popular method used by developers. This also gives us an in-depth look at what npm is and why to use it. Node Package Manager

Using jQuery and TypeScript

Publish Date:2025/04/15 Views:148 Category:TypeScript

This article provides the basic understanding and concepts of using jQuery with TypeScript. It guides on how to use jQuery in TypeScript through a coding example and outputs using various methods in TypeScript and provides knowledge about w

Checking for undefined in TypeScript

Publish Date:2025/04/15 Views:196 Category:TypeScript

This article will demonstrate how programmers can check for undefined in TypeScript using various coding examples and situations. It not only gives you an understanding of checking for undefined in TypeScript, but also helps in differentiat

exclude attribute in TypeScript

Publish Date:2025/04/15 Views:190 Category:TypeScript

This article will discuss excluding properties from a TypeScript type. The exclude property is used to create another type from an existing type with fewer or modified properties. Omit Exclude properties from types in TypeScript TypeScript

Function return types in TypeScript

Publish Date:2025/04/15 Views:174 Category:TypeScript

TypeScript is a strongly typed language and it is always encouraged to define the types correctly for all variables used in TypeScript. These types can help in development later, especially during debugging. In addition to variables, functi

Dictionary or map type in TypeScript

Publish Date:2025/04/15 Views:131 Category:TypeScript

Dictionaries or maps are used to quickly retrieve items from an object. TypeScript does not have any concept of maps or dictionaries. Plain JavaScript has objects that can set and retrieve key-value pairs. TypeScript provides Record types t

Regular expressions in TypeScript

Publish Date:2025/04/15 Views:104 Category:TypeScript

RegExp Is a regular expression used to match a fixed set of characters in a target string using TypeScript. RegExp Objects have many properties and methods. Each property has different options when pattern matching. Using regular expression

Scan to Read All Tech Tutorials

Social Media
  • https://www.github.com/onmpw
  • qq:1244347461

Recommended

Tags

Scan the Code
Easier Access Tutorial