Skip to content

Instantly share code, notes, and snippets.

@osamajavaid
Created September 24, 2023 16:16
Show Gist options
  • Save osamajavaid/63aaed12ef972477730e5d1536b22d7d to your computer and use it in GitHub Desktop.
Save osamajavaid/63aaed12ef972477730e5d1536b22d7d to your computer and use it in GitHub Desktop.
React useForm hook: Creates a stateful value from the fields in a form.
const useForm = initialValues => {
const [values, setValues] = React.useState(initialValues);
return [
values,
e => {
setValues({
...values,
[e.target.name]: e.target.value
});
}
];
};
///////////////////
// Example
///////////////////
const Form = () => {
const initialState = { email: '', password: '' };
const [values, setValues] = useForm(initialState);
const handleSubmit = e => {
e.preventDefault();
console.log(values);
};
return (
<form onSubmit={handleSubmit}>
<input type="email" name="email" onChange={setValues} />
<input type="password" name="password" onChange={setValues} />
<button type="submit">Submit</button>
</form>
);
};
ReactDOM.createRoot(document.getElementById('root')).render(
<Form />
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment