Typing Custom Event Handlers Beyond Standard Events
You'll learn how to create type-safe handlers for library-specific events and custom component callbacks that go beyond React's standard DOM events.
The Core Idea
Not all interactions in React apps use standard browser events like onClick or onChange. Third-party libraries (like drag-and-drop systems, date pickers, or chart libraries) and your own custom components often fire events with their own unique data structures. TypeScript needs explicit type definitions for these handlers to provide safety and autocomplete.
Beyond React.MouseEvent
When working with custom events, you define the shape of the callback explicitly:
// Custom drag handler from a hypothetical library
interface DragEndResult {
dragId: string;
source: { index: number };
destination: { index: number } | null;
}
interface DraggableListProps {
onDragEnd: (result: DragEndResult) => void;
}
function DraggableList({ onDragEnd }: DraggableListProps) {
const handleDragEnd = (result: DragEndResult) => {
// TypeScript knows result.source.index exists
console.log(`Moved from ${result.source.index}`);
onDragEnd(result);
};
return <div>{/* library component */}</div>;
}
Custom Component Callbacks
For your own components, define callback types that match your data:
interface FileUploadEvent {
file: File;
progress: number;
}
interface UploaderProps {
onUploadProgress: (event: FileUploadEvent) => void;
}
The pattern is simple: identify what data the callback receives, create an interface describing it, and use that interface as the function parameter type.
Key Takeaway: Type custom event handlers by defining explicit interfaces for their callback parameters—this gives you full type safety for library-specific events and custom component interactions that fall outside React's standard synthetic events.