$chiubaca / notes / fleeting / 2021-03-30
  • 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>
Edit on GitHub ✏️

Hey I'm Alex Chiu 👋. These are my notes for literally anything.

I'm using the Zettelkasten method to organise my thoughts here.

My more polished writings are published to my main blog at chiubaca.com

Follow me on: Github / X (Twitter) / Mastodon / LinkedIn