Chakra UI の toggleスイッチ + react-hook-formでデフォルト値を設定しつつ切り替え可能にする
説明
isChecked を使うとデフォルト値を設定できる。
isChecked の説明に↓と書いてある。
自分でstateやonChangeを使って切替する処理を書かなければいけない。
If true, the checkbox will be checked. You’ll need to pass onChange to update its value (since it is now controlled)
コード
const [isChecked, setIsChecked] = useState(false)
const getFromApiBool = APIから取得したbooleanの値
useEffect(() => {
setIsChecked(getFromApiBool ?? false)
}, [isAllEnable])
<Switch
colorScheme="色の名前"
{...register('react-hook-formの項目名')}
isChecked={isChecked}
onChange={() => setIsChecked(!isChecked)}
/>
参考記事
[https://chakra-ui.com/docs/components/switch:embed:cite]
[https://chakra-ui.com/docs/components/switch/props:embed:cite]