Typed events and refs in React components with Typescript
Based on how you define your event handlers you can either rely on Typescript’s inference or have to supply the types for the handlers.
If you use inline event handlers then you don’t need to provide types and can just write them like you would in a regular React project.
If you define the handler separately and then reference it with onClick for example, then you have to type the handler.
const EventComponent: React.FC = () => {
const onChange = (event: React.ChangeEvent<HTMLInputElement>) => {
// handle the event
}
return (
<div><input onChange={onChange}</div>
)
}
export default EventComponent
One easy way to figure out the type of the event if you’re using VSCode is to hover over the onClick attribute for example and copy the event type from the tooltip.