pinale
pinale

Reputation: 2214

material-ui autocomplete wrapped into react-hook-form Controller, can't get the value

I can't get the value of the field wrapped into the react-hook-form <Controller /> in the onSubmit function. What is missing? the other field works correctly

    const onSubmit = async (data,e) => {
           console.log("DATA" , data) 
           //data.groups is always undefined

           ...
    }  
    
    
    
      <form onSubmit={handleSubmit(onSubmit)}>
        
            <Controller 
                name="groups"

                control={control}
                as={() => (
                    <Autocomplete multiple options={fbGroupsData.Group} getOptionLabel={option => option.name}  renderInput={(params) =>(<TextField {...params}  variant="outlined" label="Groups" placeholder="Groups" />)}/>
                )}
            />

            <TextField fullWidth  inputRef={register} InputLabelProps={{ shrink: true }}  name="name"  label="Name" variant="outlined" />
    
         </form>

Upvotes: 2

Views: 3450

Answers (1)

Bill
Bill

Reputation: 19338

There is an example in the doc: https://codesandbox.io/s/react-hook-form-v6-controller-qsd8r which was recommended to use render prop instead of as:

    <Controller
      render={(props) => (
        <Autocomplete
          {...props}
          options={countries}
          getOptionLabel={(option) => option.label}
          renderOption={(option) => (
            <span>
              {countryToFlag(option.code)}
              {option.label}
            </span>
          )}
          renderInput={(params) => (
            <TextField
              {...params}
              label="Choose a country"
              variant="outlined"
            />
          )}
          onChange={(_, data) => props.onChange(data)}
        />
      )}
      name="country"
      control={control}
    />

Upvotes: 4

Related Questions