Skip to content

Instantly share code, notes, and snippets.

@amitasaurus
Created May 21, 2024 09:43
Show Gist options
  • Save amitasaurus/5a302b8a5d0ea84a4fbbe608742cb991 to your computer and use it in GitHub Desktop.
Save amitasaurus/5a302b8a5d0ea84a4fbbe608742cb991 to your computer and use it in GitHub Desktop.
react hook to manage form
import { useFormFields } from '../lib/hooks/useFormFields';
type Props = {};
export default function Form({}: Props) {
const [fields, handleFieldChange] = useFormFields({
email: '',
password: '',
});
function handleFormSubmit() {
console.log(fields);
}
return (
<form>
<div>
<label htmlFor="email">Enter Email</label>
<input
type="email"
name="email"
id="email"
value={fields.email}
onChange={handleFieldChange}
/>
</div>
<div>
<label htmlFor="password">Enter Password</label>
<input
type="password"
name="password"
id="password"
value={fields.password}
onChange={handleFieldChange}
/>
</div>
<button type="button" onClick={handleFormSubmit}>
Submit
</button>
</form>
);
}
import { useState, ChangeEvent, ChangeEventHandler } from 'react';
interface FieldsType {
[key: string | symbol]: string;
}
export function useFormFields(
initialState: FieldsType
): [FieldsType, ChangeEventHandler] {
const [fields, setValues] = useState(initialState);
return [
fields,
function (event: ChangeEvent<HTMLInputElement>) {
setValues({
...fields,
[event.target.id]: event.target.value,
});
return;
},
];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment