formik set field value code example

Example: setFieldValue

const Form = ({ data }) => (
  <Formik
    initialValues={data}
    ...and do some more stuff here like error handling submit handling etc...
    render={({ values, handleSubmit, handleChange, handleBlur }) => (
      <Form onSubmit={handleSubmit}>
        <Field
          name="mail.email"
          value={values.mail.mail}
          render={({ field, form }) => (
            <input
              {...field}
              onChange={e => {
                const domain = e.target.value.replace(/.*@/, '')
                handleChange(e)
                form.setFieldValue('mail.domain', domain)
              }}
            />
          )}
        />
        <input
          name="mail.domain"
          value={values.mail.domain}
          onChange={handleChange}
          onBlur={handleBlur}
        />
       <button type="submit">Submit</button>
      </Form>
    )}
  />
)

Tags:

Misc Example