How to type a Form component with onSubmit? How to type a Form component with onSubmit? reactjs reactjs

How to type a Form component with onSubmit?


This worked for me. Just guessing based on your guess. Thanks!

handlePostForm = (e: React.FormEvent) => {


You would need to specify the type of the form elements. Let's say for example in your form you have an input with id yourInputName:

<form onSubmit={handleSubmit}>  <div>    <label htmlFor="yourInputName">Username:</label>    <input id="yourInputName" type="text" />  </div>  <button type="submit">Submit</button></form>

In your handleSubmit, you would need to specify the type of the event.currentTarget. A form tag has a type of HTMLFormElement with a property elements, which are a type of HTMLFormControlsCollection, but we can override that to tell TS what our input is. Create an interface which extends the HTMLFormControlsCollection, specify the type of your field and then use the custom interface to override the elements property in the HTMLFormElement.

interface FormElements extends HTMLFormControlsCollection {    yourInputName: HTMLInputElement}interface YourFormElement extends HTMLFormElement {   readonly elements: FormElements}

Then you pass that new type to your handling function

const handleFormSubmit = (e: React.FormEvent<YourFormElement>) => {}

You can now access the value of your field and typescript will know what it is

const handleFormSubmit = (e: React.FormEvent<YourFormElement>) => {    e.preventDefault();    console.log(e.currentTarget.elements.yourInputName.value)}

If you hover on value, TS should show you a message that the data type is HTMLInputElement.value: string, just as you have specified in your FormElements interface.