Leff
Leff

Reputation: 1318

Set the on click method conditionaly in a component

I have a component with an onClick method, where I would like to set the method conditionaly based on the property I get in the component. This is how to code looks like:

      <Image
        className={styles.editIcon}
        src={openForm ? editPeriodDisabled : editPeriod}
        onClick={() => toggleFormCallback(id)}
        alt="Rediger periode"
      />

I have a boolean property openForm, by which I would like to set the method in the onClick property of the Image component. So, something like this for example:

openForm ? null : toggleFormCallback(id)

But, not sure how to do that with an arrow function?

Upvotes: 0

Views: 35

Answers (3)

Mohammed
Mohammed

Reputation: 11

This should work

<Image
  className={styles.editIcon}
  src={openForm ? editPeriodDisabled : editPeriod}
  onClick={() => !openForm && toggleFormCallback(id)}
  alt="Rediger periode"
/>

Upvotes: 0

Code-Apprentice
Code-Apprentice

Reputation: 83527

You can use bind():

onClick={openForm : null ? toggleFormCallback.bind(this, id)}

bind() returns a new function which is the same as the original but bound to the given context. You can also bind some or all of the parameters.

Upvotes: 1

Alex Antonov
Alex Antonov

Reputation: 15156

The easiest solution.

  <Image
    className={styles.editIcon}
    src={openForm ? editPeriodDisabled : editPeriod}
    onClick={() => { if (openForm) { toggleFormCallback(id) } }}
    alt="Rediger periode"
  />

Upvotes: 0

Related Questions