qweezz
qweezz

Reputation: 804

How to type React Hook Form control prop in reusable component?

I have a reusable form. This form can have different inputs depending on where it is used. I pass control as prop to this form from parent component (which holds all the logic) with type any but I'd like to have a more strict typing. How to do this?

I mean in one component an input can be like {name: ""} and another {face: "", address: ""} so how to type control prop in CreateForm so that it works with different inputs?

Parent component which holds the input logic:

type CreateFaceInput = {
      name: string;
      cover: string;
    };
    
const FaceModal = ({ open, onClose }: IFaceModalProps) => {

  const {
    handleSubmit,
    control,
  } = useForm<CreateFaceInput>({
    defaultValues: {
      name: '',
      cover: '',
    },
  });

  const onSubmit = (data: CreateFaceInput) => {};

  return (

          <CreateForm
            onSubmit={handleSubmit(onSubmit)}
            control={control}
          />
        )
  );
};

CreateForm.tsx

import { Controller } from 'react-hook-form';

interface ICreateFormProps {
  control: any;
  onSubmit: () => void; 
}

const CreateForm = ({ onSubmit, control }: ICreateFormProps) => {


  return (
      <Controller
        render={({ field, fieldState: { error } }) => (
          <StyledTextField
            {...field}
          />
        )}
        control={control}
      />
  );
};

aaaa

Upvotes: 8

Views: 8243

Answers (2)

Anusha
Anusha

Reputation: 30

It worked for me


  interface ICustomTextFieldProps<T extends FieldValues> {
      name: Path<T>;
      rules?: RegisterOptions<T>;
      control?: Control<T>;
      defaultValue?: PathValue<T, Path<T>>;
    }

const CustomTextField = <T extends FieldValues>({}:ICustomTextFieldProps<T>) => {
      return (
        <FormControl fullWidth className="custom-text-field">
                           )}
          <Controller
            name={name}
            defaultValue={defaultValue}
            control={control}
            rules={rules}
            render={({ field, fieldState: { error } }) => (
              <>
                <OutlinedInput
                
                  {...field}
                                 />
              </>
            )}
          />
        </FormControl>
      );
    };

Upvotes: 1

Sachila Ranawaka
Sachila Ranawaka

Reputation: 41397

can add FieldValues type

import { Control, FieldValues } from "react-hook-form";


interface ICreateFormProps {
     control:?: Control<FieldValues, CreateFaceInput>;

Upvotes: 6

Related Questions