4

I am attempting to use react-spring's useSprings to enable users to reorder the items in a formik FieldArray. The useSprings Draggable List demo (found here) uses useRef to manage the order of items. FieldArray comes with a number of array helper functions for inserting, removing, and moving items.

The issues that I'm having are:

1) Re-ordering existing items using formik's move array helper method successfully changes the array order, but requires an additional click to render the correct order

2) Adding or removing array items using array helper methods produces unexpected results. Mutating the length of the ref doesn't change the length of order.current inside of useGesture

I've also tried using useState instead of useRef and updating the state with useEffect when props change.

Here is a code sandbox I made: https://codesandbox.io/s/usesprings-with-fieldarray-56bex

In the bind function, commenting out

order.current = newOrder;
and uncommenting
// arrayHelpers.move(currIndex, currRow);
shows issue #1 that I mentioned above.

I would like to be able to use formik's move, insert, and remove helper functions with react-spring to seamlessly re-order, add, and delete items within a FieldArray.

Stafford Rose
  • 769
  • 4
  • 9

2 Answers2

1

maybe you can try setting the new order.current after adding the new element

  onClick={() =>{
          arrayHelpers.insert(items.length, {
            name: `Item ${items.length + 1}`
          })
          order.current = [...order.current, order.current.length];
        }
      }

this will add the new item at the end of the list.

Jose LM
  • 73
  • 1
  • 8
0

I encountered at least your #1 issue.

Note that the the setSprings function doesn't re-render anything on its own, and the useSprings is missing a dependencies array to auto-update.

react-springs@9.0.0.beta-23 has a dependencies array, and together with the useSpringsFixed wrapper in the sandbox that is linked here it should force-rerender on changed props.

Hope that helps your issue too.

bebbi
  • 2,489
  • 3
  • 22
  • 36