Reactのライブラリreact-hook-formで複数のチェックボックスが存在する場合に全てのチェックボックスにチェックする方法です。
import { useForm } from 'react-hook-form';
const Sample = () => {
const osList = ['WindowsXP', 'WindowsVista', 'Windows7', 'Windows8', 'Windows8.1', 'Windows10', 'Windows11']
const {
register,
handleSubmit,
setValue,
formState: { errors },
} = useForm();
const onSubmit = () => {
console.log();
};
return (
<form onSubmit={handleSubmit(onSubmit)}>
{osList.map((os, index) => (
<div key={index}>
<input
type="checkbox"
value={os}
{...register(`windows.${index}`, {})}
/>
<label htmlFor="">{os}</label>
</div>
))}
<input type="button" value="全てにチェック" onClick={() => {
osList.map((os, index) => {
setValue('windows', { [index]: true})
})
}} />
<input type="button" value="全てにチェックを外す" onClick={() => {
osList.map((os, index) => {
setValue('windows', { [index]: false})
})
}} />
<input type="submit" value="送信" />
</form>
);
}
export default Sample;