0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

react-sortablejsとreact-hook-formで並び替え

Posted at

入力フォームの並び替え

ドラッグ&ドロップで並び替えできるreact-sortablejsとreact-hook-formsを組み合わせた並び替えできる入力フォームの備忘録

サンプルソース

import { ReactSortable } from 'react-sortablejs'
import { useFormContext, useFieldArray } from 'react-hook-form'
import Forms from './forms'

const sortableInputs = ()=>{
    const {
        control,
        formState: { errors },
    } = useFormContext()
    
    const { fields, swap } = useFieldArray({
        name: 'contents',
        control,
    })

    const onEnd = (evt:any)=>{
        swap(evt.oldIndex, evt.newIndex)
    }

    return <>
        <ReactSortable list={fields} setList={()=>{}} onEnd={onEnd}>
          {fields &&
            fields?.map?.((field: any) => {
              return (
                <Forms
                  key={field?.id}
                  field={field}
                />
              )
            })
        }
        </ReactSortable>
    </>
}

ReactSortableではsetListではなくonEndを使う。onEndではoldIndexとnewIndexがあるので、useFieldArrayにそもそも備わっているswap()で処理ができる。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?