Twitter khuong291
Twitter khuong291

Reputation: 11672

Add onclick listener reactjs

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.

Upvotes: 0

Views: 1530

Answers (1)

Oscar Paz
Oscar Paz

Reputation: 18292

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

Upvotes: 1

Related Questions