In React, event handling is similar to handling events on DOM elements. However, with TypeScript, you have the power to utilize specific event types, like React.EventHandler<>
, to precisely define the nature of the events your components can handle.
TypeScript provides specific event types for different user interactions. For instance, for click events, you can use React.MouseEvent<>
, and for change events, React.ChangeEvent<>
is used. This helps in preventing errors, such as passing the wrong event type to a handler function.
The React.EventHandler<>
type is a generic type that can be used with various event types. For example, for a button click event, you would use:
const handleClick: React.EventHandler<React.MouseEvent<HTMLButtonElement>> = (event) => {
console.log('Button clicked!', event);
};
return <button onClick={handleClick}>Click Me</button>;
The event
argument here will be strongly typed to a click event for a <button>
element.
<input>
controlled component by adding an onChange
event handler that updates the value in the state.