Search code examples
reactjstypescriptreact-functional-componentreact-hook-form

Passing methods through child components using React-Hook-Forms


I am trying to use the register() method in my child component. But I am getting a Typescript Error saying: Expected 1-2 arguments, but got 0.

I am assuming I am passing the register method incorrectly?

Parent Component

type FormValues = {
  projectType: string;
};

const Parent = () => {
  const {
    register,
  } = useForm<FormValues>({ mode: 'all' });
  return (
    <Container>
      <FormBlock id="form">
        <fieldset>
          <ChildComponent props={register()}/>
        </fieldset>
      </FormBlock>
    </Container>
  );
};

Child Component

const ChildComponent = ({ props }) => {
  return (
    <InputField {...props.register('projectType')}></InputField
  );
};

Solution

  • You've to update the following line to:

    <ChildComponent props={register} />
    

    You shouldn't call register, you've to remove the parenthesis

    EDIT: thanks to Calvin

    You've to edit the component:

    <InputField {...props('projectType')}></InputField>
    

    It's cleaner to rename props to register

    <ChildComponent register={register} />
    
    // Field
    <InputField {...register('projectType')}></InputField>