Techumber
Home Blog Work

React Handling form onSubmit event

Published on March 10, 2023

When building a form in a React application with TypeScript, handling the onSubmit event requires some additional considerations. Here are some steps you can follow to handle the form onSubmit event in React with TypeScript:

Define the form fields and state types: Before you can handle the form submit event, you need to define the types for the form fields and the state they will be stored in. This is important for TypeScript to ensure that you are accessing and modifying the state correctly. For example, you can define a LoginFormState interface that includes the email and password fields as follows:

interface LoginFormState {
  email: string;
  password: string;
}

Initialize the state: In your component constructor or by using the useState hook, you can initialize the state object with the form fields you defined in step 1:

const [formState, setFormState] = useState<LoginFormState>({
  email: '',
  password: ''
});

Handle input changes: To handle changes to the form fields, you can use the onChange event on each input field to update the state. For example:

<input type="email" value={formState.email} onChange={(e) => setFormState({ ...formState, email: e.target.value })} />
<input type="password" value={formState.password} onChange={(e) => setFormState({ ...formState, password: e.target.value })} />

Define the onSubmit function: The onSubmit function is called when the user clicks the submit button on the form. In this function, you can handle any validation and submit the form data to the server. Here’s an example onSubmit function that logs the form data to the console:

const handleSubmit = (e: React.FormEvent<HTMLFormElement>) => {
  e.preventDefault();
  console.log(formState);
};

Note that we are preventing the default form submission with e.preventDefault().

Add the onSubmit event to the form: Finally, you can add the onSubmit event to the form and call the handleSubmit function. For example:

<form onSubmit={handleSubmit}>
  {/* form fields */}
  <button type="submit">Submit</button>
</form>

These are the basic steps involved in handling the form onSubmit event in React with TypeScript. Of course, you may need to customize the validation and submission logic based on your specific requirements.