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
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
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
Top comments (0)