0

I want to add callback function when I click to button.

My code:

export enum PAYMENT_METHOD {
  online,
  offline,
}

interface Props {
  paymentMethod: PAYMENT_METHOD;
  togglePaymentMethod: (paymentMethod: PAYMENT_METHOD) => void;
}

const AmountToPayModal = (props: Props) => (
  <Container>
    <SectionLabel>
  2.&nbsp;
  <FormattedMessage id="SE-206.Section2.Title" />
</SectionLabel>
<PaymentBox>
      <PaymentButtonDeselected >
        <FormattedMessage id="SE-206.Section2.OnlinePayment" />
      </PaymentButtonDeselected>
      <PaymentButtonSelected onClick={props.togglePaymentMethod(PAYMENT_METHOD.online)}>
        <FormattedMessage id="SE-206.Section2.OfflinePayment" />
      </PaymentButtonSelected>
    </div>
</PaymentBox>
</Container>
    );

[ts] Type '{ onClick: void; children: Element; }' is not assignable to type 'IntrinsicAttributes & IntrinsicClassAttributes, any>>'. Types of property 'onClick' are incompatible. Type 'void' is not assignable to type 'EventHandler> | undefined'.

I am using TypeScript.

1 Answer 1

1

In your onClick handler you're not passing a function, but the call to a function. Your function will be called when the AmountToPayModal is called (during render), not when the user makes a click. And that function returns void, so TypeScript infers (correctly) that you're assigning void to an event handler.

I think that what you really want to to do is this:

<PaymentButtonSelected onClick={() => props.togglePaymentMethod(PAYMENT_METHOD.online)}>

Now you're assigning a function to the handler, and when the user clicks the element, your function will be called correctly

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks @Oscar Paz
Lambdas are forbidden in JSX attributes due to their rendering performance impact

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.