My application utilizes the react-hook-forms
library along with the office-ui-fabric-react
framework.
To integrate the framework inputs, I wrap the 3rd party component using the <Controller>
element.
The current setup is functional as shown below:
<Controller
control={control}
name={"Value"}
rules={{ required: true }}
render={({ field, fieldState, formState }) => (
<TextField
value={field.value}
errorMessage={fieldState.error?.message}
label={field.name}
description={"Value of the property"}
onChange={(_, value) => field.onChange(value)}
onBlur={field.onBlur}
required
/>
)}
/>
Since this method appears lengthy, I aim to streamline it by creating a new component called ControlledTextField
.
I anticipate using it in the following way:
<ControlledTextField
control={control}
name={'Value'}
rules={{ required: true }}
label={'Value'}
description={"Value of the property"}
required
/>
In an attempt to implement this, I made the following adjustments:
type ControllerPropsEx = Omit<ControllerProps, "render" | "control" | "name">;
// Base type for controlled inputs
type ControlledType<F extends FieldValues, T> = {
name: Path<F>;
control: Control<F>;
controllerProps?: ControllerPropsEx;
} & T;
// customized props for TextField component, merged with controller props
// and excluding props already handled by react hook form
type ControlledTextFieldProps<F extends FieldValues> = ControlledType<
F,
Omit<ITextFieldProps, "onChange" | "onBlur" | "value" | "errorMessage"> // Exclude properties managed by the controller
>;
const ControlledTextField = <F extends FieldValues>({
name,
control,
controllerProps,
...props
}: ControlledTextFieldProps<F>): JSX.Element => {
return (
<Controller
name={name}
control={control}
{...controllerProps}
render={({
field: { onBlur, onChange, value, name },
fieldState: { error }
}) => (
<TextField
{...props}
name={name}
value={value || ""}
onChange={onChange}
onBlur={onBlur}
errorMessage={error?.message}
/>
)}
/>
);
};
Despite these modifications, I encountered compile errors. Specifically, I received the
Type 'Control<F, any>' is not assignable to type 'Control<FieldValues, any>'
error relating to control={control}
How can I effectively categorize my component's prop types?
For a comprehensive code snapshot, visit the code sandbox repro (referencing NonWorkingForm.tsx file)