【React Hook Form×Material UI】 defaultValue, defaultCheckedが効かない時に確認すること

React Hook Form(以下RHF)とMaterial UIを組み合わせた、defaultValue系にハマりやすいので備忘録です。

useFormのresetを実行しているか

APIでdefaultValueをフェッチするときにやることです。
RHFは最初に渡ってきたdefaultValueをキャッシュするので、defaultValueを変更するにはresetする必要があります。

const Sample: React.FC = () => {
  const { sample } = useFetchSampleData()
  const { reset } = useForm()

  useEffect(() => {
    reset({
      defaultValue: {
        title: sample.title,
        text: sample.text
      }
    })  
  }, [reset, sample])

  return (
    <div>{*/ ... /*}</div>
  )
}

チェックボックスのdefaultCheckedの設定位置

ChcekboxにdefaultCheckedを渡します。

import { Radio, Checkbox, FormControlLabel } from '@mui/material'
import { useForm, Controller } from 'react-hook-form'

...

<Controller
  name='gender'
  control={control}
  render={(): JSX.Element => (
    <>
      <FormControlLabel
        name='color'
        label='BLUE'
        value='blue'
        control={<Checkbox defaultChecked={getValues('color').includes('blue')} />}
      />
      <FormControlLabel
        name='color'
        label='RED'
        value='red'
        control={<Checkbox defaultChecked={getValues('color').includes('red')} />}
      />
  </>
   )}
/>

ラジオボタンのdefaultCheckedの設定位置

ラジオボタンはRadioGroupにdefaultValueを付与します。
defaultCheckedではなくdefaultValueです。

import { Radio, Checkbox, FormControlLabel } from '@mui/material'
import { useForm, Controller } from 'react-hook-form'

...

<Controller
  name='fruit'
  control={control}
  render={(): JSX.Element => (
    <RadioGroup row name='fruit' defaultValue={getValues('fruit')}>
      <FormControlLabel
        label='BANANA'
        value='banana'
        control={<Radio />}
      />
      <FormControlLabel
        label='APPLE'
        value='apple'
        control={<Radio />}
      />
    </RadioGroup>
  )}
/>
タイトルとURLをコピーしました