2
votes

I have configured an Autocomplete and a DatePicker component using Material UI 5.

How to add react hook form support? My AutoComplete tag looks like this:

const { itemsIdFormHookRef, ...itemsIdFormHookRest } = register("itemsId", {
    required: true
});

<Autocomplete
    options={state.itemsList}
    getOptionLabel={(item) => (item.name ? item.name : "")}
    getOptionSelected={(option, value) =>
      value === undefined || value === "" || option.id === value.id
    }
    value={
      state.itemIdSelected
        ? state.itemsList.find(
            (item) => item.id === state.itemIdSelected
          )
        : ""
    }
    onChange={(event, items) => {
      if (items !== null) {
        dispatch({
          type: SET_ITEM_ID,
          payload: items.id
        });
      }
    }}
    renderInput={(params) => (
      <TextField
        {...params}
        {...itemsIdFormHookRest}
        label="items"
        margin="normal"
        variant="outlined"
        inputRef={itemsIdFormHookRef}
        error={errors.itemsId ? true : false}
        helperText={errors.itemsId && "item required"}
        required
      />
    )}
  />

The attached codesandbox example was working in very similar fashion with react-hook-form V6.

But with react hook form V7 my default values are not validated:

https://codesandbox.io/s/react-hook-form-v7-material-ui-5-hz7j6

1

1 Answers

3
votes

First off, in your code here:

const { itemsIdFormHookRef, ...itemsIdFormHookRest } = register(...);
const { fromFormHookRef, ...fromFormHookRest } = register(...);

register() never returns itemsIdFormHookRef or fromFormHookRef property but it returns a ref so maybe what you mean is this:

const { ref: itemsIdFormHookRef, ...itemsIdFormHookRest } = register(...);
const { ref: fromFormHookRef, ...fromFormHookRest } = register(...);

If you want react-hook-form to validate your default value, you need to pass those values to the defaultValues property when calling useForm instead of keeping your initialState in a separate variable:

const {...} = useForm({
  defaultValues: {
    itemsId: 1,
    fromDate: new Date()
  }
});

Live Demo

Edit 67068456/react-hook-form-v7-material-ui-5-default-values-not-validated