traintocode

React Event Handlers

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.

Event Types

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.

Using React.EventHandler

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.

Exercise
Complete the <input> controlled component by adding an onChange event handler that updates the value in the state.
    You cannot do the coding exercises on this device, visit this page on a larger screen.
    App.tsx
    Loading...