-
-
Save alexander-elgin/4869e50479dc8a567f397f1928a96868 to your computer and use it in GitHub Desktop.
Formik with MobX
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
function useFormik(props) { | |
// useState to keep the same observable around without recreating it on each render | |
const [formik] = React.useState(() => | |
mobx.observable({ | |
values: props.initialValues || {}, | |
touched: {} | |
}) | |
) | |
// just mutate state, this function itself can be considered an action+reducer | |
const handleChange = fieldName => event => { | |
formik.values[fieldName] = event.target.value; | |
}; | |
const handleBlur = fieldName => event => { | |
formik.touched[fieldName] = true; | |
}; | |
// props will be spread over the form inputs minimizing code necessary to setup such input | |
const getFieldProps = fieldName => ({ | |
value: formik.values[fieldName], | |
onChange: handleChange(fieldName), | |
onBlur: handleBlur(fieldName) | |
}); | |
return { handleChange, handleBlur, getFieldProps, ...formik }; | |
} | |
function NameForm() { | |
// use the formik hook with optional initial values | |
const formik = useFormik({ | |
initialValues: { | |
name: "", | |
email: "" | |
} | |
}); | |
const { getFieldProps } = formik; | |
// notice the useObserver hook that takes care of re-rendering | |
return useObserver(() => ( | |
<form> | |
<label> | |
Name: | |
<input type="text" {...getFieldProps("name")} /> | |
</label> | |
<label> | |
Email: | |
<input type="text" {...getFieldProps("email")} /> | |
</label> | |
<Debug formik={formik} /> | |
<button type="submit">Submit</button> | |
</form> | |
)); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment