Home > Blockchain >  React forms hook with Material UI Select input not working
React forms hook with Material UI Select input not working

Time:12-24

How de Select below the Textfield should load:

enter image description here

How it actually loads:

enter image description here

My Select component created using Material UI React form hook doesn't load the default value. (The component should start with a value selected, that is provided once in the following part of the code)

  const clientData = await api.client.getClient(id);
  reset({ ...clientData });

It happens inside a useEffect that should run once, when the page is loaded and the id is gotten from the url. The Select code:

export const ClientSourceSelect = ({
      control,
      clientSources,
      getValues,
      errors,
    }: ClientSourceSelectProps) => (
      <FormControl fullWidth>
        <Controller
          control={control}
          name="clientSourceId"
          render={({ field: { onChange, value } }) => (
            <>
              <TextField label={value}></TextField>
              <Select onChange={onChange} value={value}>
                {clientSources.map((clientSource) => (
                  <MenuItem key={clientSource.id} value={clientSource.id}>
                    {clientSource.name}
                  </MenuItem>
                ))}
              </Select>
            </>
          )}
        />
      </FormControl>
    );

I created the TextField over the Select to test if the value is really loaded, and the value is really displayed over the Select (a uuid corresponding to clientSource.id), so the value itself exists but the Select starts blank. Using the inspector, the li elements have a correct data-value attribute with their corresponding id.

CodePudding user response:

Based on the documentation, you can provide default values when calling useForm() hook.

const { control } = useForm({
  defaultValues: {
    clientSourceId: <your default id>
  }
});

Your working code can be found in this sandbox: https://codesandbox.io/s/young-sun-7ee953

  • Related