In this post, we’ll cover 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. 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.
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
:
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:
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