Search code examples
typescript

Pass function as prop in TypeScript


How to pass a function as a property? I've simplified the following, but the parent contains an array of data items (emailDetails) to be displayed, along with a function to delete one of them (emailDeleteHandler) that I'd like to pass down to a child:

   const [emailDetails, setEmailDetails] = useState<EmailVerification[] | null>(null);

   const emailDeleteHandler = (emailAddress: string): void => { // operations here}

   return (
      <div>
         childFunction(emailDetails || [], emailDeleteHandler)
      <div/>
   )

so that when the child function is called, it can use it as in per the following:

export interface EmailVerification {
    email: string
    required: boolean
}

export function childFunction(
    emailDetails: EmailVerification[],
    emailDeleteHandler: ##something goes here##
) {
    const emailToBeDeleted = 'emailToBeDeleted';
    return (
        <div>
            <button onClick={() => {
                emailDeleteHandler(emailToBeDeleted);
            }}>
                Delete from account
            </button>
        </div>)
}

There are two areas I'm struggling to understand:

  • In the child component, what do I need to replace ##something goes here## with to ensure syntactic compliance?

  • In the parent component, how would I pass the function emailDeleteHandler to the child?


Solution

  • try to replace emailDeleteHandler: ##something goes here## with this emailDeleteHandler: (email: string)=> void