Skip to content

Instantly share code, notes, and snippets.

@truongluu
Last active April 15, 2023 12:18
Show Gist options
  • Save truongluu/31e0b5a746ea251b01a56d5584ee4c0a to your computer and use it in GitHub Desktop.
Save truongluu/31e0b5a746ea251b01a56d5584ee4c0a to your computer and use it in GitHub Desktop.
How to type a React Form with submit handler
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