Search code examples
javascriptreactjsreact-hook-formnextui

Can not register Checkbox of NextUI to react-hook-form


I am coding a ReactJS project. I use react hook form to handle form submitting and NextUI (NU) as a UI library.

When I register a checkbox of NU like this:

<form onSubmit={handleSubmit(onSubmitLogin)}>
 <Checkbox defaultSelected {...register('remember')}>
  <Text size={14}>Remember me</Text>
 </Checkbox>
</form>

Then I submit a form:

const onSubmitLogin = (form) => {
 console.log(form);
};

But the response I claimed from the console log is:

{
    email: "[email protected]"
    password: "sadsad"
    remember: undefined
}

Note: I use raw input of HTML (no using NextUI for email and password input) and register => success. However, when I register for checkbox of NextUI, it log undefined value. How can I register for checkbox as well as input of NextUI to react-hook-form

Edit: More detail, when I check a checkbox, the console shoot an error:

Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'name')


Solution

  • I think the Checkbox component from NextUI is a controlled component so when using react-hook-form you can wrap the Checkbox component in the Controller component from react-hook-form:

    <Controller
      control={control}
      name='remember'
      render={({ field: { onChange, value } }) => (
          <Checkbox defaultSelected onChange={onChange} isSelected={value}>
              <Text size={14}>Remember me</Text>
          </Checkbox>
      )}
    />