Skip to content

Instantly share code, notes, and snippets.

@eric-mathison
Created May 17, 2020 04:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save eric-mathison/d2f337e5838dc651dec0e02286eef79e to your computer and use it in GitHub Desktop.
Save eric-mathison/d2f337e5838dc651dec0e02286eef79e to your computer and use it in GitHub Desktop.
useForm Hook for forms in Bootstrap
import useForm from './useForm';
function Form() {
const callback = () => {
console.log(values);
};
const { values, handleChange, handleSubmit, validated } = useForm(callback);
return (
<Form
noValidate
validated={validated}
onSubmit={handleSubmit}
>
<Form.Group controlId="email">
<Form.Label>Email Address</Form.Label>
<Form.Control
type="email"
name="email"
placeholder="e.g tinkerman@email.com"
onChange={handleChange}
value={values.email || ''}
required
/>
<Form.Control.Feedback type="invalid">
Please enter your email address.
</Form.Control.Feedback>
</Form.Group>
<Form.Group controlId="password">
<Form.Label>Password</Form.Label>
<Form.Control
type="password"
name="password"
onChange={handleChange}
value={values.password || ''}
required
/>
<Form.Control.Feedback type="invalid">
Please enter your password.
</Form.Control.Feedback>
</Form.Group>
<Button
variant="primary"
type="submit"
>
Sign in
</Button>
</Form>
);
}
export default Form;
import React from 'react';
function useForm(callback, validate) {
const [values, setValues] = React.useState({});
const [validated, setValidated] = React.useState(false);
const handleSubmit = (event) => {
event.preventDefault();
const form = event.currentTarget;
if (form.checkValidity() === false) {
setValidated(true);
} else {
callback();
}
};
const handleChange = (event) => {
event.persist();
setValues((values) => ({
...values,
[event.target.name]: event.target.value,
}));
};
return {
handleChange,
handleSubmit,
values,
validated,
};
}
export default useForm;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment