Created
November 20, 2020 02:51
-
-
Save dhruvilp/9805c6e05858ccc8b559c66219116476 to your computer and use it in GitHub Desktop.
React Forms w/ Hooks
This file contains hidden or 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
| function useFormFields<T>(initialValues: T) { | |
| const [formFields, setFormFields] = React.useState<T>(initialValues); | |
| const createChangeHandler = (key: keyof T) => ( | |
| e: React.ChangeEvent<HTMLInputElement>, | |
| ) => { | |
| const value = e.target.value; | |
| setFormFields((prev: T) => ({ ...prev, [key]: value })); | |
| }; | |
| return { formFields, createChangeHandler }; | |
| } | |
| export function LoginForm() { | |
| const { formFields, createChangeHandler } = useFormFields({ | |
| email: "", | |
| password: "", | |
| }); | |
| const handleSubmit = (e: React.FormEvent) => { | |
| e.preventDefault(); | |
| api.login(formFields.email, formFields.password); | |
| }; | |
| return ( | |
| <form onSubmit={handleSubmit}> | |
| <div> | |
| <label htmlFor="email">Email</label> | |
| <input | |
| type="email" | |
| id="email" | |
| value={formFields.email} | |
| onChange={createChangeHandler("email")} | |
| /> | |
| </div> | |
| <div> | |
| <label htmlFor="password">Password</label> | |
| <input | |
| type="password" | |
| id="password" | |
| value={formFields.password} | |
| onChange={createChangeHandler("password")} | |
| /> | |
| </div> | |
| </form> | |
| ); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment