uber
uber

Reputation: 5073

Can I access a value in Formik before onSubmit is run?

I am trying to do some maths over a value that the user inputs

<Form>
    <label htmlFor={`price${props.id}`}>Price</label>
       <Field
          name={`price${props.id}`}
          type="text"
       />
       <ErrorMessage name={`price${props.id}`} />
       <span> </span> //Where I want to display value
      ...

This is how I am using Formik. Form is simply nested inside of Formik:

<Formik
          initialValues={{
            [`price${props.id}`]: '',
}}

          onSubmit={(values, { setSubmitting }) => {
            setTimeout(() => {
              alert(JSON.stringify(values, null, 2))
              setSubmitting(false)
          }, 400)
}}>
    <Form>
     ....
    </Form>
</Formik>

Upvotes: 1

Views: 6346

Answers (2)

larz
larz

Reputation: 5766

<Formik> can provide a child function that will allow you to access all of it's props, including current values -

<Formik>
  {{ values } => (
    <Form>
      <label htmlFor={`price${props.id}`}>Price</label>
      <Field
        name={`price${props.id}`}
        type="text"
      />
      <ErrorMessage name={`price${props.id}`} />
      <span>
        // will show the current value, or you can do calculations
        {values[`price${props.id}`]}
      </span>
    </Form>
  )}
</Formik>

Upvotes: 1

Callum Hart
Callum Hart

Reputation: 214

Formik accepts two types of children:

  1. React node
  2. Function that returns a React node

Currently you are passing a React node to Formik (#1).

In order to access values you need to change the child to a function (#2), which is known as a render prop.

Values can then be accessed like so:

<Formik 
  initialValues={/* ... */} 
  onSubmit={/* ... */}
>
  {props => (
    <form>
      {/* here we can access props.values */}
    </form>
  )}
</Formik>

A full list of what props contain can be found here.

Upvotes: 1

Related Questions