0

I am using React Hook Form. I've made a custom checkbox which looks like this:

const Checkbox = ({ text, className, setCheckbox, checkbox }) => {
  const { register } = useFormContext();
  const statute = register("statute");
  return (
    <Wrapper className={className}>
      <StyledLabel>
        <div>{text}</div>
        <StyledInput
          type="checkbox"
          name="statute"
          onChange={(e) => {
            statute.onChange(e);
            setCheckbox && setCheckbox(!checkbox);
          }}
        />
        <Checkmark />
      </StyledLabel>
    </Wrapper>
  );
};

Checkbox (Checkbox.js) is nested in a parent component (Register.js):

const Register = ({ setRegisterView }) => {
  const validationSchema = Yup.object().shape({
    statute: Yup.bool().oneOf([true], "You need to accept the page statute."),
  });

  const methods = useForm({
    mode: "onSubmit",
    resolver: yupResolver(validationSchema),
  });

  const {
    register: validate,
    formState: { errors },
    handleSubmit,
  } = methods;

  return (
    <Wrapper>
      <FormProvider {...methods}>
        <Form onSubmit={handleSubmit(registerProcess)}>
          <StyledCheckbox
            text="Accept the page statute."
            setCheckbox={null}
            checkbox={null}
          />
          {errors.statute && <Error>{errors.statute.message}</Error>}
          <LoginButton type="submit">SIGN UP</LoginButton>
        </Form>
      </FormProvider>
    </Wrapper>
  );
};

export default Register;

The problem is that when I check the checkbox I get an information in errors.statute.message: statute must be a `boolean` type, but the final value was: `"on"`..

When I change this:

onChange={(e) => {
            statute.onChange(e);
            setCheckbox && setCheckbox(!checkbox);
          }}

to this:

{...register("statute")}

then it works great and errors.statute.message shows correct message just when checked=false in checkbox input. But I need to have the extended version of onChange.

0

1 Answer 1

1

The problem is, that you not link the returned ref of the register call to your <StyledInput />. So just spread the return value of register - in the code example below i also omitted the name prop as it is included in statute. Here you can find all the props register will return.

<StyledInput
  type="checkbox"
  {...statute}
  onChange={e => {
    statute.onChange(e);
    setCheckbox && setCheckbox(!checkbox);
  }}
/>

Edit StyledInput (forked)

Sign up to request clarification or add additional context in comments.

1 Comment

Yes that's it! It works great now! Thank You!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.