Dzmitry Shchepin
Dzmitry Shchepin

Reputation: 81

How can I use formik "arrayHelper" outside of FieldArray?

I trying to create 2 FieldArray containers with arrayHelpers. Each of them working with different object. Obj1 and Obj2 have their arrayHelper and each of them know how to add and remove objects to/from array.

I want to do some kind of toolbar with two buttons "Add Obj1" and "Add Obj2" outside of these two containers. The question is how can I work with arrayHelper outside of these containers? Or could you suggest another flow how can change my array? The problem is if I change my array from parent - I can't work with props.values only with props.obj1 but in this case my changes are not saving.

<FieldArray name="obj1"
                    render={arrayHelpers => {}/>
<FieldArray name="obj2"
                    render={arrayHelpers => {}/>

<div class="toolbar">...buttons</div>

Upvotes: 7

Views: 7828

Answers (2)

Faris Hadibrata
Faris Hadibrata

Reputation: 11

I might be late, but maybe this would help someone with this issue.

Create ref for ArrayHelper

const ArrayHelperRef = useRef()

and inside your FieldArray assign the ref

 <FieldArray
          name="friends"
          render={(arrayHelpers) => {
            ArrayHelperRef.current = arrayHelpers
            return (
              <div>
                {values.friends && values.friends.length > 0 ? (
                  values.friends.map((friend, index) => (
                    <div key={index}>
                      <Field name={`friends.${index}`} />
                    </div>
                  ))
                ) : (
                  <button
                    type="button"
                    onClick={() => arrayHelpers.push('')}
                  >
                    Add a friend
                  </button>
                )}
              </div>
            )
          }}
        />

And use it like this

 <button onClick={() => {ArrayHelperRef.current.push('')}}>Add new</button>

Upvotes: 1

Stafford Rose
Stafford Rose

Reputation: 807

To access arrayHelpers outside of a FieldArray, you can use refs.

I've created a code sandbox, showing how you can do this:

https://codesandbox.io/s/using-refs-to-access-child-methods-cps7w

Upvotes: 3

Related Questions