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

Time:11-30

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

CodePudding user response:

can add FieldValues type

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


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