[Feature Request]: Add Array Fields move method
t-rosa opened this issue · comments
Description
When working with array fields, it would be interesting to be able to call a "move(from: number, to: number)" method simply to move an element from one index to another, which is particularly useful for implementing a drag-and-drop mechanism.
Here's an example:
function App() {
const form = useForm({
defaultValues: {
people: [],
},
onSubmit({ value }) {
alert(JSON.stringify(value))
},
})
return (
<div>
<form
onSubmit={(e) => {
e.preventDefault()
e.stopPropagation()
void form.handleSubmit()
}}
>
<form.Field name='people'>
{(field) => {
return (
<DragDropContext
onDragEnd={(event) => {
const { active, over } = event
if (!over) return
if (active.id !== over.id) {
field.moveValue(active.id, over.id)
}
}}
>
<div>
{field.state.value.map((_, i) => {
return (
<form.Field key={i} name={`people[${i}].name`}>
{(subField) => {
return (
<div>
<label>
<div>Name for person {i}</div>
<input
value={subField.state.value}
onChange={(e) =>
subField.handleChange(e.target.value)
}
/>
</label>
</div>
)
}}
</form.Field>
)
})}
<button onClick={() => field.pushValue({ name: '', age: 0 })} type='button'>
Add person
</button>
</div>
</DragDropContext>
)
}}
</form.Field>
</form>
</div>
)
}