Published on

How to Type the onSubmit event in React (TypeScript)?

How to Type the onSubmit event in React (TypeScript)?

How to Type the onSubmit event in React (TypeScript)?

How to Type the onSubmit event in React (TypeScript)?

TypeScript is a typed superset of JavaScript that adds optional static type checking to the language. This means that TypeScript can help you catch errors in your code before you even run it. One of the benefits of using TypeScript is that it can help you type your event handlers. This can make your code more readable and maintainable.

What is the onSubmit event?

The onSubmit event is a React event that is fired when a form is submitted. You can use the onSubmit event to handle user interaction, such as validating the form data or submitting it to a server.

How to type the onSubmit event in React (TypeScript)

To type the onSubmit event in React (TypeScript), you need to specify the type of the event handler function. The type of the event handler function is always a function that takes a form event object as an argument and returns void.

For example, the following code types the onSubmit event handler function for a form element:

import React, { FormEvent } from "react";

const Form: React.FC<{}> = () => {
  const handleSubmit = (event: FormEvent<HTMLFormElement>) => {
    // Handle the onSubmit event
  };

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

export default Form;

The handleSubmit() function takes a form event object as an argument and returns void. This means that the function can perform any operation that it needs to perform, such as validating the form data or submitting it to a server.

Using the onSubmit event in React (TypeScript)

Once you have typed the onSubmit event handler function, you can use it in your React code like any other function. However, it is important to remember that the event handler function will be passed a form event object as an argument. This means that you can use the event object to access information about the submit event, such as the form element that was submitted and the form data.

For example, the following code logs the form data to the console when the user submits the form:

import React, { FormEvent } from "react";

const Form: React.FC<{}> = () => {
  const handleSubmit = (event: FormEvent<HTMLFormElement>) => {
    console.log(event.target.elements);
  };

  return (
    <form onSubmit={handleSubmit}>
      <input type="text" name="name" />
      <input type="email" name="email" />
      <button type="submit">Submit</button>
    </form>
  );
};

export default Form;

When the user submits the form, the following output will be logged to the console:


  //output
  { name: "John Doe", email: "john.doe@example.com" }

I hope this helps!