Last active
April 15, 2023 12:18
-
-
Save truongluu/31e0b5a746ea251b01a56d5584ee4c0a to your computer and use it in GitHub Desktop.
How to type a React Form with submit handler
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React from 'react'; | |
export type GenHTMLFormControlsCollection<T> = HTMLFormControlsCollection & { | |
[inputName in keyof T]: HTMLInputElement; | |
}; | |
interface GenericFormElement<T extends { [inputName: string]: HTMLInputElement }> | |
extends HTMLFormElement { | |
readonly elements: GenHTMLFormControlsCollection<T>; | |
} | |
function SubmitFormHandler() { | |
const onSumitForm = ( | |
event: React.FormEvent< | |
GenericFormElement<{ usernameInput: HTMLInputElement; passwordInput: HTMLInputElement }> | |
>, | |
) => { | |
event.preventDefault(); | |
console.log('usernameInput', event.currentTarget.elements.usernameInput.value); | |
console.log('passwordInput', event.currentTarget.elements.passwordInput.value); | |
}; | |
return ( | |
<form onSubmit={onSumitForm}> | |
<input name='usernameInput' /> | |
<input name='passwordInput' /> | |
<input type='submit'>Submit</input> | |
</form> | |
); | |
} | |
export default SubmitFormHandler; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment