-
Today has been about learning about working with forms in React with Formik in the deep end. Took me a while to grok the API but I think I finally get it now.
- The form state is can be initialised with an object of any shape in the
initialValues
prop.
<Formik initialValues={{ name: 'jared', items: ['happy', 'sad', 'mad'] }} onSubmit={(values, actions) => { setTimeout(() => { alert(JSON.stringify(values, null, 2)); actions.setSubmitting(false); }, 1000); }} > {// ...components } </Formik>
- Accessing individual parts of the
initialValues
object can be acheived with the<Field />
component
<Formik initialValues={{ name: "jared", items: ["happy", "sad", "mad"] }}> <Field as="select" name="color"> <option value="red">Red</option> <option value="green">Green</option> <option value="blue">Blue</option> </Field> </Formik>
- I think programmatic mutation can also be done by utalising the render prop to render more jsx
<Formik initialValues={{ name: 'jared', items: ['happy', 'sad', 'mad'] }} > <Field name="color" render={()=>( <Button onClick={(e)=>{ e.value = 'pink'; }}> )}> </Formik>
- The form state is can be initialised with an object of any shape in the