7ce84b2e43004e00a1dc
·2 min read

Event Handling with TypeScript in React: Two ways

react
typescript
event
event-handling
4d5fd787ac74e0caa4f7

Sohan R. Emon

Developer, Learner, Tech Enthusiast

Handling events in a React application is a fundamental part of creating interactive and dynamic user interfaces. With TypeScript, you can take advantage of static typing to catch potential errors at compile-time, making your code more robust. In this blog, we'll explore two ways of handling events in React using TypeScript

Explicit Type Annotations

tsx
import * as React from 'react';

const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
  e.preventDefault();
  console.log('Input value:', e.target.value);
};

const handleKeyPress = (e: React.KeyboardEvent<HTMLInputElement>) => {
  if (e.key === 'Enter') {
    e.preventDefault();
    console.log('Enter key pressed');
  }
};

const handleClick = (e: React.MouseEvent<HTMLButtonElement>) => {
  e.preventDefault();
  console.log('Button clicked');
};

const handleFormSubmit = (e: React.FormEvent<HTMLFormElement>) => {
  e.preventDefault();
  console.log('Form submitted');
};

function EventHandlingExplicit() {
  return (
    <div>
      <input type="text" onChange={handleInputChange} onKeyDown={handleKeyPress} />
      <button onClick={handleClick}>Click me</button>
      <form onSubmit={handleFormSubmit}>
        <button type="submit">Submit Form</button>
      </form>
    </div>
  );
}

export default EventHandlingExplicit;

In this example, we've added specific event handlers for ChangeEvent, KeyboardEvent, MouseEvent, and FormEvent.

Using EventHandler Functions

tsx
import * as React from 'react';

const handleInputChange: React.ChangeEventHandler<HTMLInputElement> = (e) => {
  e.preventDefault();
  console.log('Input value:', e.target.value);
};

const handleKeyPress: React.KeyboardEventHandler = (e) => {
  if (e.key === 'Enter') {
    e.preventDefault();
    console.log('Enter key pressed');
  }
};

const handleClick: React.MouseEventHandler = (e) => {
  e.preventDefault();
  console.log('Button clicked');
};

const handleFormSubmit: React.FormEventHandler = (e) => {
  e.preventDefault();
  console.log('Form submitted');
};

function EventHandlingImplicit() {
  return (
    <div>
      <input
        type="text"
        onChange={handleInputChange}
        onKeyDown={handleKeyPress}
      />
      <button onClick={handleClick}>Click me</button>
      <form onSubmit={handleFormSubmit}>
        <button type="submit">Submit Form</button>
      </form>
    </div>
  );
}

export default EventHandlingImplicit;

In this approach, we've continued to use MouseEventHandler for mouse events and explicitly specified the KeyboardEvent for keypress handling. You can extend this pattern for other event types, such as FormEvent, as needed.

Both of these approaches allow you to handle various event types with TypeScript in a type-safe manner.

Happy Coding

Found this useful?