Search code examples
reactjsmaterial-uireact-hook-form

React Hook Forms + Material UI Checkboxes


I am having an error when submiting a form build using React Hook Form and material-ui checkboxes components. The number of checkboxes are build from a list from my api:

        <Grid item xs={12}>
          <FormControl
            required
            error={errors.project?.stack ? true : false}
            component='fieldset'>
            <FormLabel component='legend'>Tech Stack</FormLabel>
            <FormGroup>
              <Grid container spacing={1}>
                {techs.map((option, i) => (
                  <Grid item xs={4} key={i}>
                    <FormControlLabel
                      control={
                        <Checkbox
                          id={`stack${i}`}
                          name='project.stack'
                          value={option.id}
                          inputRef={register({required: 'Select project Tech Stack'})}
                        />
                      }
                      label={option.name}
                    />
                  </Grid>
                ))}
              </Grid>
            </FormGroup>
            <FormHelperText>{errors.project?.stack}</FormHelperText>
          </FormControl>
        </Grid>

When the form is submited I got the following error ( several times , 1 for each checkbox rendered ) :

Uncaught (in promise) Error: Objects are not valid as a React child (found: object with keys {type, message, ref}). If you meant to render a collection of children, use an array instead.

I don't understand this error. The message apparently says it is a rendering issue, but the component renders fine. The problems happens on submit. Any advices ?

Thank you


Solution

  • I managed to make it work without using Controller. The props should be inside the FormControlLabel and not inside Checkbox

                    <Grid item xs={4} key={i}>
                        <FormControlLabel
                          value={option.id}
                          control={<Checkbox />}
                          label={option.name}
                          name={`techStack[${option.id}]`}
                          inputRef={register}
                        />
                      </Grid>
                    ))}