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?

react-hook-formで全てのチェックボックスのチェックする方法

Posted at

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;
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?