Last active
December 22, 2018 18:53
-
-
Save malerba118/dc8b6be27d7e0d5cdfe07ac8b48bafa1 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
| // Skipping some boilerplate: imports, ReactDOM, etc. | |
| export const useField = (name, form, { defaultValue } = {}) => { | |
| let [value, setValue] = useState(defaultValue); | |
| let field = { | |
| name, | |
| value, | |
| onChange: e => { | |
| setValue(e.target.value); | |
| } | |
| }; | |
| // Register field with the form | |
| form.addField(field); | |
| return field; | |
| }; | |
| export const useForm = ({ onSubmit }) => { | |
| let fields = []; | |
| const getFormData = () => { | |
| // Get an object containing raw form data | |
| return fields.reduce((formData, field) => { | |
| formData[field.name] = field.value; | |
| return formData; | |
| }, {}); | |
| }; | |
| return { | |
| onSubmit: async e => { | |
| e.preventDefault(); // Prevent default form submission | |
| return onSubmit(getFormData()); | |
| }, | |
| addField: field => fields.push(field), | |
| getFormData | |
| }; | |
| }; | |
| const Field = ({ label, name, value, onChange, ...other }) => { | |
| return ( | |
| <FormControl className="field"> | |
| <InputLabel htmlFor={name}>{label}</InputLabel> | |
| <Input value={value} onChange={onChange} {...other} /> | |
| </FormControl> | |
| ); | |
| }; | |
| const App = props => { | |
| const form = useForm({ | |
| onSubmit: async formData => { | |
| window.alert("Account created!"); | |
| } | |
| }); | |
| const usernameField = useField("username", form, { | |
| defaultValue: "" | |
| }); | |
| const passwordField = useField("password", form, { | |
| defaultValue: "" | |
| }); | |
| const confirmPasswordField = useField("confirmPassword", form, { | |
| defaultValue: "" | |
| }); | |
| return ( | |
| <div id="form-container"> | |
| <form onSubmit={form.onSubmit}> | |
| <Field {...usernameField} label="Username" /> | |
| <Field {...passwordField} label="Password" type="password" /> | |
| <Field {...confirmPasswordField} label="Confirm Password" type="password" /> | |
| <Button type="submit">Submit</Button> | |
| </form> | |
| </div> | |
| ); | |
| }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment