Skip to content

Instantly share code, notes, and snippets.

@dhruvilp
Created November 20, 2020 02:51
Show Gist options
  • Select an option

  • Save dhruvilp/9805c6e05858ccc8b559c66219116476 to your computer and use it in GitHub Desktop.

Select an option

Save dhruvilp/9805c6e05858ccc8b559c66219116476 to your computer and use it in GitHub Desktop.
React Forms w/ Hooks
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