Search code examples
swapreact-hook-form

Nest Array Swap Problem In React-Hook-Form


Describe the problem

I have an array within an array and when I make a swap in the items of the parent array.

To Reproduce

here is demo example codesandbox

I inited two elements in parent array. And click Button:[swap section]. It can works well

enter image description here

When I click Button:[add section], there have three elements. And then click Button:[swap section], first parent's childs and second parent's childs don't swap rightly.

enter image description here

i hope it can swap rightly


Solution

  • You're providing a custom key while React Hook Form needs the field component to have its own generated id to be able to track the field's position.

    To achieve your desired behavior, you need to pass field.id (section.id in your example) to the top field element.

    {sectionsFields.map((section, sectionIndex) => {
      return (
        <div key={section.id}> // pass the RHF provide field id as the component key instead of refreshSelect + sectionIndex 
          ...
        </div>
      );
    })}