0
votes

to use Material-ui in react-hook-form you should use <Controller and the method render instead of "as = {xy-control}" Also should not mix controller and inputRef = {register}. A single control is also no problem. But there is a compound control in Material-ui. "FormControlLabel + CheckBox" how do you integrate this control in the controller. All my attempts have failed.

This is how it works but I would like the FormControlLaben to be enclosed by the controller. Does somebody has any idea?

                 <Controller
                    name="password"
                    control={control}
                    defaultValue={""}
                    render={(props) => <TextField {...props}
                                                  variant="outlined"
                                                  margin="normal"
                                                  required
                                                  fullWidth
                                                  label="Password"
                                                  type="password"
                                                  id="password"
                                                  autoComplete="current-password"
                    />}
                />

                <FormControlLabel
                    control={
                        <Checkbox
                            inputRef={register}
                            name="remember"
                        />
                    }
                    label="remember"
                />


{/*That works, but it requires an OnChange. Why can't the controller bind it?*/}
                <FormControlLabel
                    control={
                        <Controller
                            name={"remember2"}
                            control={control}
                            render={(props) => (
                                <Checkbox
                                    {...props}
                                    onChange={(e) => props.onChange(e.target.checked)}

                                />
                            )}
                        />
                    }
                    label="remember"
                />
2

2 Answers

1
votes

Here's how I did it

<FormControlLabel
  control={
    <Controller
      control={control}
      inputRef={register}
      name='controlName'
      render={({onChange, value}) => (
        <Checkbox
          onChange={e => onChange(e.target.checked)}
          checked={value}
        />
      )}
    />
  }
  label="This is a label"
/>
1
votes

From v7, I used this :

    <Controller
        name='contactAutre'
        control={control}
        defaultValue={false}
        render={({ field }) => (
            <FormControlLabel
                control={<Checkbox {...field} />}
                label='Autre'
            />
        )}
    />