Course contentsShow
← React
Lesson 2353 of 2,39651. TypeScript with React BasicsFree lesson

Typing Form Submit Handlers

Type onSubmit handlers with React.FormEvent and prevent default behavior with proper TypeScript signatures.

Typing Form Submit Handlers

You'll learn how to correctly type onSubmit handlers in React forms and prevent default browser behavior with TypeScript.

The Core Pattern

When you handle form submissions in React, you need two things: the correct event type and a way to prevent the browser's default form submission. TypeScript gives you React.FormEvent for typing these handlers, which captures form-specific events.

The standard signature looks like this:

const handleSubmit = (event: React.FormEvent<HTMLFormElement>) => {
  event.preventDefault();
  // Your form logic here
};

Why React.FormEvent?

Just like React.MouseEvent targets click events and React.ChangeEvent targets input changes, React.FormEvent is specifically designed for form submission events. The generic parameter <HTMLFormElement> tells TypeScript exactly which element fired the event, giving you proper autocomplete and type safety.

Inline vs Named Handlers

You can type handlers inline in JSX:

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

Or extract them as named functions (cleaner for complex logic):

function LoginForm() {
  const handleSubmit = (event: React.FormEvent<HTMLFormElement>) => {
    event.preventDefault();
    // Process form data
  };

  return <form onSubmit={handleSubmit}>...</form>;
}

The preventDefault Pattern

Calling event.preventDefault() is crucial—it stops the browser from refreshing the page. TypeScript ensures this method exists on React.FormEvent, catching errors if you use the wrong event type.

Key Takeaway: Type form submission handlers with React.FormEvent<HTMLFormElement> and always call event.preventDefault() to control the submission behavior in your React application instead of letting the browser handle it.