Home > database >  React Typescript: Pass function as props with arguments
React Typescript: Pass function as props with arguments

Time:05-29

So this problem has been hanging over me for the past few days and I swear I have looked just about everyone trying to solve it. I simply need to call a function passed from a parent component onClick inside of a child component. The function takes in parameters, and the parameters part is where the error lies.

I am aware that I could probably export and import the function but this is something I could do easily in regular JavaScript and react so I'm sure it must be doable. I am just not the most competent with TypeScript at the moment.

Parent Component

// Promise Function I am passing to the child
  function parentFunction(email: string, password: string, userName: string) {
    return promiseFunction(email, password)
      .then((result) => {
        return updateProfile({
          displayName: userName,
        })
      })
      .catch((error) => {
        console.log(error);
      });
  }

// Passing to child component
return (
    <div>
        <ChildComponent parentFunction = {parentFunction}/>
    </div>
)

Child Component

So because it is an onClick function I know I need to handle the event function.

type Props = {
    parentFunction: (event: React.MouseEvent<HTMLButtonElement>) => Promise<void>;
}

export default function childComponent(props: Props){
    return(
        <button onClick={props.parentFunction}></button>
    )
}

Type Issues

Now if there were no parameters there would be no problems and the function would work on click fine. However.

The function is of type

parentFunction(email: string, password: string, userName: string): Promise<void>

The onClick function is of type

MouseEventHandler<HTMLButtonElement>

I have tried adding the parameters in the Props type function but that only satisfies the function type issues, the onClick type issue still exists and vise a versa.

My attempt at solving the issue

type Props = {
  parentFunction: (
    email: string,
    password: string,
    userName: string
    event?: React.MouseEvent<HTMLButtonElement>
  ) => Promise<void>;
}

Am I going about this wrong? Am I completely missing something vital to passing functions in typescript? Any help would be greatly appreciated.

CodePudding user response:

You can try like this

To add event handler for child component

export default function childComponent(props: Props){
    return(
        <button onClick={(e) => props.parentFunction(e)}></button>
    )
}

The handler type could be like below

type Props = {
   parentFunction: (event: MouseEvent<HTMLButtonElement>: e, email?: string, password?: string, userName?: string) => Promise<void>;
}

Actual event handler

  const parentFunction = (event: MouseEvent<HTMLButtonElement>: e, email?: string, password?: string, userName?: string) => ...
  • Related