简体   繁体   中英

How can I access formik helpers insider formik wrapper component to set field value of a particular field

I am following a tutorial to create a multistep form with formik by creating a formik wrapper component. So far it works for normal field elements. But I have certain scenarios where I wish to use setFieldValue to set some values of custom component, the formik helpers are inaccessible to the child elements of the wrapper. Can someone help me on how can I use formik helpers to set values of a child element of a wrapper.

Here is the example link which I am following.

This is what I am trying to achieve -

 <FormikStepper
  initialValues={{...values}}
  onSubmit={someFunction}
  onReset={() => {}}> 
<FormikStep label='Step 1' validationSchema={Step1ValidationSchema}>
<label>Some Label</label>
 <input
  name='image'
  type='file'
  className=''
  onChange={(e) => {setFieldValue("image", e.target.files[0]);}}
  />
<ErrorMessage name='image'/>
</FormikStep>

How can I be able to access it for setting the value of a child. I tried creating a context but I am confused on where to initialize the context.ie As to where and how should I initialize the context for this particular scenario.

Better way is to extract input into separate component and then you can use setFieldValue inside that component:

const ImageInput = (props) = {
 const [setFieldValue] = useFormikContext()
 ...
}

The reason why it works is that all your components wrapper by formik Form .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM