How to make react-hook-form require 1 checkbox?

Viewed 48

I have a Checkbox component which works fine, until I had a Yup schema:

const Checkbox = React.forwardRef(
  (
    {
      label,
      name,
      value,
      onChange,
      defaultChecked,
      errors,
      onBlur,
      ...rest
    }: any,
    forwardedRef: any
  ) => {
    return (
      <div className="grow w-full">
        <label htmlFor={name}>{label}</label>
        <input
          type="checkbox"
          value={value}
          name={name}
          onChange={onChange}
          onBlur={onBlur}
          ref={forwardedRef}
          {...rest}
        />
        {errors && <p className="error">{errors.message}</p>}
      </div>
    );
  }
);

Which I use like this:

export default function App() {
  const {
    handleSubmit,
    register,
    formState: { errors }
  } = useForm({
    resolver: yupResolver(schema)
  });

  const onSubmit = (data: any) => {
    console.log("clicked");
    console.log(errors, "errors");
    alert(JSON.stringify(data));
  };

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <Checkbox
        {...register("name", { required: "This is required." })}
        name={"name"}
        value={"test"}
        label={"Test"}
        errors={errors.name}
      />
      <Checkbox
        {...register("name", { required: "This is required." })}
        name={"name"}
        value={"test"}
        label={"Test"}
        errors={errors.name}
      />
      <button type="submit">Submit</button>
    </form>
  );
}

When I go to submit my form, I get the following error:

name must be a `array` type, but the final value was: `null` (cast from the value `false`). If "null" is intended as an empty value be sure to mark the schema as `.nullable()`

Here's my sandbox

Here's the code I followed to get me to this stage - to me it looks the same? Can't see where I've gone wrong here

0 Answers
Related