How to Implement React Event Handlers with TypeScript

How to Implement React Event Handlers with TypeScript

Learn how to implement React event handlers that have strongly-typed parameters with TypeScript. The React event system is a wrapper around the browser’s native event system. TypeScript types for this event system are available in the @types/react npm package. These types can be used to strongly-type event parameters.

In this post, we’ll cover how to implement React event handlers that have strongly-typed parameters with TypeScript.

React event types

The React event system is a wrapper around the browser’s native event system. TypeScript types for this event system are available in the @types/react npm package. These types can be used to strongly-type event parameters. Some of the common ones are:

  • ChangeEvent<T>
  • KeyboardEvent<T>
  • MouseEvent<T>
  • FormEvent<T>

These types are all derived from SyntheticEvent<T>.

All the event types are generic and take in the type for the element that raised the event. For example, MouseEvent<HTMLButtonElement> could be used for the parameter type for a button click handler.

Inline event handlers

If the event handler is implemented inline in the JSX element, it is automatically strongly-typed. Consider the example below:

<input
  type="text"
  value={criteria}
  onChange={(e) =>
    setCriteria(e.currentTarget.value)
  }
/>

TypeScript is able to infer the type of e to be ChangeEvent<HTMLInputElement>. So, we get nice autocompletion when we reference e:

Inline handler autocomplete

Named event handlers

The typing is a little more tricky when a named function is used for the event handler. Consider the example below:

function Searchbox() {
  const [criteria, setCriteria] = React.useState(
    ""
  );
  const handleChange = (e) => {    setCriteria(e.currentTarget.value);  };  return (
    <input
      type="text"
      value={criteria}
      onChange={handleChange}
    />
  );
}

TypeScript infers the type of the e parameter in handleChange to be any. So, no type checking will occur when e is referenced in the handler implementation.

Not good!

We can use a type annotation to define the type of e explicitly. What type should e be set to? Well, a neat tip is to hover over the event handler prop to find out:

Hover tip

So, the type is ChangeEvent<HTMLInputElement>. So, a strongly-typed version of the handleChange event handler is as follows:

const handleChange = (
  e: React.ChangeEvent<HTMLInputElement>) => {
  setCriteria(e.currentTarget.value);
};

Neat!

react typescript javascript programming developer

Bootstrap 5 Complete Course with Examples

Bootstrap 5 Tutorial - Bootstrap 5 Crash Course for Beginners

Nest.JS Tutorial for Beginners

Hello Vue 3: A First Look at Vue 3 and the Composition API

Building a simple Applications with Vue 3

Deno Crash Course: Explore Deno and Create a full REST API with Deno

How to Build a Real-time Chat App with Deno and WebSockets

Convert HTML to Markdown Online

HTML entity encoder decoder Online

How native is React Native? | React Native vs Native App Development

Article covers: How native is react native?, React Native vs (Ionic, Cordova), Similarities and difference between React Native and Native App Development.

Hire Dedicated React Native Developer

Have you ever thought of having your own app that runs smoothly over multiple platforms? React Native is an open-source cross-platform mobile application framework which is a great option to create mobile apps for both Android and iOS. **[Hire...

Hire Dedicated React Native Developer in India | React Native Development

Hire dedicated React Native developers for your next project. As the top react native development company we offer you the best service as per your business needs.

Hire React Js Developer from Expert React JS Development Company

Are you looking to [hire React JS developer](https://www.mobiwebtech.com/react-js-development-company/ "hire React JS developer") from a prestigious and reliable React JS development company? Visit at Mobiweb Technologies here we have a big team...

How to Migrate a React Component from JavaScript to TypeScript

Learn how to easily migrate a React component from JavaScript to TypeScript to improve your project. When migrating over to TypeScript, one basic thing to keep in mind is TypeScript files have a .ts extension instead of .js. Another thing to keep in mind that makes migrating over a breeze is that you can configure your TypeScript compiler to allow JavaScript files.