Created
May 17, 2020 04:38
-
-
Save eric-mathison/d2f337e5838dc651dec0e02286eef79e to your computer and use it in GitHub Desktop.
useForm Hook for forms in Bootstrap
This file contains 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
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; |
This file contains 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
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