React Event Handling and Event Types

Learn to type React click, change, and form handlers in TypeScript, pass callbacks through props, and validate user input safely with clear examples.

published: reading time: 9 min read author: Geek Workbench
Quick Summary

React handlers receive browser events, while callback props pass a smaller application action between components. This guide types change and submit events, shows when JSX can infer a handler signature, and explains when a native listener needs cleanup. It also covers runtime validation, since TypeScript's event types cannot limit what a person enters.

React event handling and event types

Introduction

React event handlers are functions passed to elements through props such as onClick and onChange. TypeScript can infer the event type when a handler is written in JSX. When you move the function elsewhere, an explicit type makes its expected element and event clear.

This guide types common click, change, and submit handlers, and shows how callbacks carry behavior between components.

Click and change handlers

An inline handler gets its event type from the JSX prop. If you pull it out into a named function, annotate the event with the element it handles:

import type { ChangeEvent } from "react";

interface FilterInputProps {
  value: string;
  onValueChange: (value: string) => void;
}

function FilterInput({ value, onValueChange }: FilterInputProps) {
  const handleChange = (event: ChangeEvent<HTMLInputElement>) => {
    onValueChange(event.currentTarget.value);
  };

  return (
    <div>
      <label>
        Filter tasks
        <input value={value} onChange={handleChange} />
      </label>
      <button type="button" onClick={() => onValueChange("")}>
        Clear
      </button>
    </div>
  );
}

The input event is typed for an HTMLInputElement. The clear button needs no event details, so its inline function can call the application callback directly.

Form submission and callback props

A form’s submit handler receives a form event. Calling preventDefault() keeps the browser from navigating away before your React code handles the values:

import { useState, type FormEvent } from "react";

interface SignupFormProps {
  onCreate: (email: string) => Promise<void>;
}

function SignupForm({ onCreate }: SignupFormProps) {
  const [email, setEmail] = useState("");
  const [pending, setPending] = useState(false);
  const [error, setError] = useState("");

  const handleSubmit = async (event: FormEvent<HTMLFormElement>) => {
    event.preventDefault();
    if (pending) return;

    const value = email.trim();
    if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value)) {
      setError("Enter a valid email address.");
      return;
    }

    setPending(true);
    setError("");
    try {
      await onCreate(value);
    } catch {
      setError("The request failed. Try again.");
    } finally {
      setPending(false);
    }
  };

  return (
    <form onSubmit={handleSubmit}>
      <label>
        Email
        <input
          type="email"
          value={email}
          onChange={(event) => setEmail(event.currentTarget.value)}
          required
        />
      </label>
      {error && <p role="alert">{error}</p>}
      <button type="submit" disabled={pending}>
        {pending ? "Creating account…" : "Create account"}
      </button>
    </form>
  );
}

This basic check catches an empty or malformed address, and the pending state disables the submit button while the request runs. The server still needs its own validation and, where retries matter, an idempotency strategy. See Fetching and Typing API Data for request cancellation and stale-response handling.

A callback prop is a function contract between components. It does not need to expose the React event if the child only needs to report an action:

interface DeleteButtonProps {
  itemId: string;
  onDelete: (itemId: string) => void;
}

function DeleteButton({ itemId, onDelete }: DeleteButtonProps) {
  return <button onClick={() => onDelete(itemId)}>Delete</button>;
}

The button’s onClick is a React event handler, while onDelete is an application callback. Keeping them separate lets the parent decide what deletion means without coupling it to a mouse event.

React props and DOM listeners

In JSX, onClick takes a function and React calls it when the user clicks. It is a prop managed by React. A browser addEventListener call also takes a function, but it registers directly on a DOM node and needs lifecycle cleanup if that node or component goes away. Use JSX handlers for ordinary interface actions; use DOM listeners only when integrating with an API that requires them.

flowchart LR
    A[User action] --> B[Browser event]
    B --> C[React handler]
    C --> D[State update or callback]
    D --> E[Component renders again]

Trade-off table

Situation Use Trade-off
Small action used once Inline JSX function Compact, but complex logic can crowd the markup
Logic needs a name or reuse Named handler Easier to read and reuse; annotate its event parameter
Child reports a domain action Callback prop Keeps child independent of parent behavior
Third-party API requires a native listener addEventListener Direct browser control, but cleanup is your responsibility

Production failure scenarios

A form may reload the page because the browser submits it before the app handles the action. Attach a handler to the <form> itself and call event.preventDefault() first. Then check that the submit button has type="submit"; a button outside the form or marked type="button" will not trigger that submit handler. A second failure is a destructive action firing twice on rapid clicks. Disable the control while the request is pending and make the server operation safe to retry.

Common pitfalls / anti-patterns

  • Pass a function: use onClick={handleClick}, not onClick={handleClick()} unless you intend to call it during render.
  • Use event.currentTarget when you need the element associated with this handler.
  • Let JSX infer inline event types; annotate extracted handlers with the matching element type.
  • Call preventDefault() for a form when handling submission in React.
  • Do not call a handler during render unless that is intentional.
  • Do not assume TypeScript makes input values trusted or test only the happy path.

Observability checklist

  • Check the browser console and React DevTools when a handler does not run.
  • Use a temporary log or breakpoint to confirm event and currentTarget.
  • Exercise keyboard submission, invalid values, and repeated clicks.

Security and compliance notes

TypeScript event types only help while compiling. A value read from an input is still user-controlled text, even if your state variable is annotated as number. Parse and validate values before using them in calculations, requests, or decisions. Server-side code must validate them too.

When to use / when not to use

Use JSX handlers for ordinary clicks and form submissions, and callback props when a child reports a domain action. Use native listeners only when an integration requires them and you can clean them up. Avoid passing raw browser events through layers that only need a value such as an item ID.

Quick recap checklist

  • JSX usually infers inline event types; annotate named handlers.
  • Match the event type to the element, such as ChangeEvent<HTMLInputElement>.
  • Use callbacks for component-to-parent actions that do not need the raw event.
  • Handle form submission on the form and prevent navigation when appropriate.
  • Validate user input at runtime; TypeScript cannot make it trustworthy.

Interview questions

1. When should you annotate a React event parameter?

Inline JSX handlers usually get a contextual event type. Annotate the parameter when you declare a handler separately, using the event type and element type that match its use.

2. What is the difference between an event handler and a callback prop?

A handler receives a UI event such as a click. A callback prop communicates an application action, such as deleting an item, and can pass only the data the parent needs.

3. Why use currentTarget instead of target?

currentTarget is the element whose handler is running, so its TypeScript type matches the handler annotation. target may be a nested element that originated the event.

4. What does onClick={handleClick} pass to React?

It passes the function so React can call it when the event occurs.

  • onClick={handleClick()} calls it during rendering.
  • Use a wrapper when the handler needs an argument.
5. Which element should handle form submission?

Put the handler on the form's onSubmit prop.

  • Call preventDefault() when React handles the submission.
  • Use a submit button inside the form.
6. When would addEventListener be appropriate?

Use a native listener when integrating with an API that requires direct DOM events.

  • Register it against the correct element.
  • Remove it during cleanup when the node or component is no longer active.
7. Why should a domain callback avoid taking a DOM event?

A callback that takes a value such as an item ID keeps the parent independent of the child's control.

  • The child translates its click into an application action.
  • The parent does not need to know which element produced it.
8. Does ChangeEvent validate the input value?

No. It describes the event and element to TypeScript at compile time.

  • Input values are still user-controlled strings.
  • Parse and validate them before using them as trusted data.
9. What does a void callback type tell the caller?

It says the callback's return value is not used by that contract.

  • (itemId: string) => void describes a focused action.
  • Represent async completion explicitly if callers need to await it.
10. How can you keep a destructive event safe from repeat clicks?

Disable or mark the control pending while work is in progress.

  • Give users clear feedback about the pending action.
  • Make server operations safe to retry where possible.

Further reading

Conclusion

Use React’s JSX handlers for normal interface events, let contextual typing handle inline functions, and annotate named handlers at the boundary. Keep callbacks focused on application actions. Then validate the input at runtime, because an event type describes code expectations, not what a person can type.

Category

Related Posts

Controlled Inputs and Forms in React

Learn to control form values with React state, type change and submit events, show validation feedback, and handle form data safely with TypeScript.

#react #typescript #forms

React Props, Children, and Component Composition

Learn to pass data and callbacks through React props, use children for flexible layouts, and compose small components without building giant prop APIs.

#react #typescript #components

React Custom Hooks for Reusable Stateful Logic

Learn how React custom hooks reuse stateful logic, follow use* naming and call rules, type inputs and results, and keep each call's state independent.

#react #typescript #custom-hooks