Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access Formik's values outside of component | React

Tags:

reactjs

formik

Some info

I am using Formik for my project and I have my setup looking like this:

|-MenuModal
|--MenuEdit
|---MenuEditForm

Where MenuModal is the parent to MenuEdit and MenuEditForm. The component MenuEditForm is responsible for returning the Formik form, but I am calling the submit in it's parent MenuModal, which laters runs the submit function in MenuEdit via React's refs. Messy? Yup!

My problem

Right now I am trying to use state and callback functions to get the Formiks values from MenuEditForm to MenuEdit. But since I am not using Formiks own onSubmit:

    <Formik
        initialValues={menu}
        validationSchema={validationSchema}
        onSubmit={values => console.log('values', values)} // 'values' is undefined
        ...

My values will be undefined and I can't make my submit function go through.

So I wonder how I can access my values in MenuEditForm so I later can pass it up to MenuEdit and complete my submit function.

Thanks for reading.

like image 216
Martin Nordström Avatar asked Jul 16 '18 14:07

Martin Nordström


People also ask

How do you access Formik field values?

it is very simple just do console. log(formik. values) and you will get all the values without submitting it.

What is useFormikContext?

useFormikContext() is a custom React hook that will return all Formik state and helpers via React Context.

How do you reset a specific field in Formik?

If you want to reset the selected value after the form is submitted, you need to provide a controlled value for the Select component. The Formik Field component provides the value in the props object, so you can use it.

How does Formik handle onChange?

Formik will automagically inject onChange , onBlur , name , and value props of the field designated by the name prop to the (custom) component. children can either be an array of elements (e.g. <option> in the case of <Field as="select"> ) or a callback function (a.k.a render prop).


2 Answers

To access values outside of the formik component, you can do this with hooks:

      const formRef = useRef();

      return (
        <Formik
          ...
          innerRef={formRef}
        >
        ...
      </Formik>

Then, can access values using formRef.current.values anywhere outside of the component.

like image 111
Jordan Daniels Avatar answered Sep 20 '22 05:09

Jordan Daniels


Since formik passes value to onChangeText we can save it in useState for dynamic updates

  onChangeText={(value: string) => {
      handleChange('name')(value);
      setName(value);
  }}
like image 36
Sehrish Waheed Avatar answered Sep 18 '22 05:09

Sehrish Waheed