Lesson 58 of 60 – Typing React Events
97%

Typing React Events

React applications frequently respond to user actions such as clicking buttons, typing in input fields, submitting forms, and changing selections. TypeScript provides event types that help us correctly handle these events.

Note: React event types are available through the React package. Common types include React.MouseEvent, React.ChangeEvent, and React.FormEvent.

1. What are React Events?

Events allow a React component to respond to user actions.

  • Button clicks
  • Input changes
  • Form submission
  • Mouse actions
  • Keyboard actions
  • Selection changes
<button onClick={handleClick}>
    Click Me
</button>

2. Why Type React Events?

TypeScript helps us understand which properties and methods are available on an event object.

  • Provides better editor suggestions.
  • Prevents incorrect event usage.
  • Makes event handlers easier to understand.
  • Improves code safety.

3. Basic Click Event

function handleClick() {
    console.log("Button clicked");
}

return (
    <button onClick={handleClick}>
        Click
    </button>
);

When the button is clicked, handleClick is called.

4. Typing a Mouse Click Event

function handleClick(
    event: React.MouseEvent<HTMLButtonElement>
): void {

    console.log(event.currentTarget);
}

The generic parameter specifies the HTML element that generated the event.

5. MouseEvent Type

React.MouseEvent is commonly used for mouse events.

function handleClick(
    event: React.MouseEvent
): void {

    console.log(event.clientX);
    console.log(event.clientY);
}

The event object provides information about the mouse interaction.

6. MouseEvent with a Button

function handleClick(
    event: React.MouseEvent<HTMLButtonElement>
): void {

    console.log(
        event.currentTarget.textContent
    );
}

return (
    <button onClick={handleClick}>
        Save
    </button>
);

7. ChangeEvent

React.ChangeEvent is commonly used for input value changes.

function handleChange(
    event: React.ChangeEvent<HTMLInputElement>
): void {

    console.log(event.target.value);
}

8. Typing an Input Event

function handleChange(
    event: React.ChangeEvent<HTMLInputElement>
): void {

    console.log(
        event.target.value
    );
}

return (
    <input
        type="text"
        onChange={handleChange}
    />
);

9. Input with useState

const [name, setName] =
    useState<string>("");

function handleChange(
    event: React.ChangeEvent<HTMLInputElement>
): void {

    setName(event.target.value);
}

return (
    <input
        value={name}
        onChange={handleChange}
    />
);

10. Textarea Events

A textarea uses HTMLTextAreaElement.

function handleChange(
    event: React.ChangeEvent<HTMLTextAreaElement>
): void {

    console.log(
        event.target.value
    );
}

return (
    <textarea
        onChange={handleChange}
    />
);

11. Select Change Event

function handleChange(
    event: React.ChangeEvent<HTMLSelectElement>
): void {

    console.log(
        event.target.value
    );
}

return (
    <select onChange={handleChange}>

        <option value="react">
            React
        </option>

        <option value="typescript">
            TypeScript
        </option>

    </select>
);

12. Checkbox Change Event

function handleChange(
    event: React.ChangeEvent<HTMLInputElement>
): void {

    console.log(
        event.target.checked
    );
}

return (
    <input
        type="checkbox"
        onChange={handleChange}
    />
);

The checked property gives the checkbox state.

13. FormEvent

React.FormEvent can be used for form submission events.

function handleSubmit(
    event: React.FormEvent<HTMLFormElement>
): void {

    event.preventDefault();

    console.log("Form submitted");
}

14. Preventing Form Submission

function handleSubmit(
    event: React.FormEvent<HTMLFormElement>
): void {

    event.preventDefault();

    console.log("Submitted");
}

return (
    <form onSubmit={handleSubmit}>

        <button type="submit">
            Submit
        </button>

    </form>
);

preventDefault() prevents the browser's default form submission behavior.

15. Keyboard Events

Keyboard events can be typed using React.KeyboardEvent.

function handleKeyDown(
    event: React.KeyboardEvent<HTMLInputElement>
): void {

    console.log(event.key);
}

16. onKeyDown Event

function handleKeyDown(
    event: React.KeyboardEvent<HTMLInputElement>
): void {

    if (event.key === "Enter") {
        console.log("Enter pressed");
    }
}

return (
    <input
        onKeyDown={handleKeyDown}
    />
);

17. Focus Events

Focus events can be typed using React.FocusEvent.

function handleFocus(
    event: React.FocusEvent<HTMLInputElement>
): void {

    console.log(
        "Input focused"
    );
}

return (
    <input onFocus={handleFocus} />
);

18. Blur Events

function handleBlur(
    event: React.FocusEvent<HTMLInputElement>
): void {

    console.log(
        "Input lost focus"
    );
}

return (
    <input onBlur={handleBlur} />
);

onBlur runs when an element loses focus.

19. Mouse Enter Event

function handleMouseEnter(
    event: React.MouseEvent<HTMLDivElement>
): void {

    console.log("Mouse entered");
}

return (
    <div onMouseEnter={handleMouseEnter}>
        Move mouse here
    </div>
);

20. Passing Event Handlers as Props

interface ButtonProps {
    onClick: (
        event: React.MouseEvent<HTMLButtonElement>
    ) => void;
}

function MyButton({
    onClick
}: ButtonProps) {

    return (
        <button onClick={onClick}>
            Save
        </button>
    );
}

Event handlers can be typed when they are passed from a parent component to a child component.

21. Event Handler Without Explicit Event Type

TypeScript can often infer the event type when the handler is written directly inside JSX.

return (
    <input
        onChange={(event) => {
            console.log(event.target.value);
        }}
    />
);

In this situation, TypeScript understands the event based on the JSX element.

22. Inline Click Event

return (
    <button
        onClick={(event) => {
            console.log(
                event.currentTarget
            );
        }}
    >
        Click
    </button>
);

Inline event handlers can also receive an automatically inferred event object.

23. React Native Events

React Native has its own event types because it uses native components instead of HTML elements.

import {
    TextInput
} from "react-native";

function App() {

    const handleChange = (
        value: string
    ): void => {

        console.log(value);

    };

    return (
        <TextInput
            onChangeText={handleChange}
        />
    );
}

Here, onChangeText directly provides the new text value.

24. React Native Button Events

import {
    Button
} from "react-native";

function App() {

    const handlePress = (): void => {
        console.log("Button pressed");
    };

    return (
        <Button
            title="Save"
            onPress={handlePress}
        />
    );
}

React Native's Button uses onPress for button interaction.

25. React Native TextInput Event Types

import {
    TextInput
} from "react-native";

function App() {

    const handleChangeText = (
        text: string
    ): void => {

        console.log(text);

    };

    return (
        <TextInput
            onChangeText={handleChangeText}
            placeholder="Enter name"
        />
    );
}

The onChangeText callback receives a string, making it simple to type.

26. Common Event Typing Mistakes

  • Using an HTML event type for a React Native component.
  • Using HTMLInputElement for a button event.
  • Forgetting the correct React event type.
  • Confusing target and currentTarget.
  • Using the wrong element type in React.MouseEvent.
  • Using browser-specific event types in React Native.

27. Event Handler Return Type

Event handler functions that do not return a value can be explicitly typed as void.

const handleClick = (
    event: React.MouseEvent<HTMLButtonElement>
): void => {

    console.log(
        event.currentTarget
    );
};

28. Typed Form Example

import {
    useState
} from "react";

function LoginForm() {

    const [email, setEmail] =
        useState<string>("");

    const handleChange = (
        event: React.ChangeEvent<HTMLInputElement>
    ): void => {

        setEmail(event.target.value);
    };

    const handleSubmit = (
        event: React.FormEvent<HTMLFormElement>
    ): void => {

        event.preventDefault();

        console.log(email);
    };

    return (
        <form onSubmit={handleSubmit}>

            <input
                type="email"
                value={email}
                onChange={handleChange}
            />

            <button type="submit">
                Login
            </button>

        </form>
    );
}

29. Best Practices for Typed Events

  • Use the correct React event type for each event.
  • Specify the correct HTML element type when needed.
  • Use ChangeEvent for controlled input changes.
  • Use FormEvent for form submission.
  • Use MouseEvent for mouse interactions.
  • Use KeyboardEvent for keyboard interactions.
  • Let TypeScript infer inline event types when it can.
  • Use React Native-specific callback signatures for native components.

30. Complete Typed Events Example

import {
    useState
} from "react";

function StudentForm() {

    const [name, setName] =
        useState<string>("");

    const [course, setCourse] =
        useState<string>("React");

    const handleNameChange = (
        event: React.ChangeEvent<HTMLInputElement>
    ): void => {

        setName(event.target.value);
    };

    const handleCourseChange = (
        event: React.ChangeEvent<HTMLSelectElement>
    ): void => {

        setCourse(event.target.value);
    };

    const handleSubmit = (
        event: React.FormEvent<HTMLFormElement>
    ): void => {

        event.preventDefault();

        console.log({
            name,
            course
        });
    };

    const handleReset = (
        event: React.MouseEvent<HTMLButtonElement>
    ): void => {

        setName("");
        setCourse("React");

        console.log(
            event.currentTarget
        );
    };

    return (
        <form onSubmit={handleSubmit}>

            <h2>
                Student Form
            </h2>

            <input
                type="text"
                value={name}
                placeholder="Enter name"
                onChange={handleNameChange}
            />

            <br />
            <br />

            <select
                value={course}
                onChange={handleCourseChange}
            >

                <option value="React">
                    React
                </option>

                <option value="TypeScript">
                    TypeScript
                </option>

                <option value="React Native">
                    React Native
                </option>

            </select>

            <br />
            <br />

            <button type="submit">
                Save
            </button>

            <button
                type="button"
                onClick={handleReset}
            >
                Reset
            </button>

        </form>
    );
}

export default StudentForm;

This example combines typed input events, select events, form events, mouse events, state, and event handler return types in one component.

📌 Key Points

  • React events allow components to respond to user actions.
  • React.MouseEvent is used for mouse events.
  • React.ChangeEvent is commonly used for input changes.
  • React.FormEvent is used for form submission.
  • React.KeyboardEvent is used for keyboard events.
  • React.FocusEvent is used for focus and blur events.
  • TypeScript can often infer inline event types automatically.
  • React Native uses native component event APIs such as onPress and onChangeText.
  • Correct event typing makes React and React Native applications easier to maintain.

🧠 Quick Quiz

Question: Which React event type is commonly used for an HTML input's onChange event?