1

I have a React component where I am passing onClick function. I originally just had button.onClick, but I need to check if isBannerClickable is false before setting this. If isBannerClickable === true, then I don't want to set onClick.

Is it possible to simplify or clean this onClick prop?

onClick={!!isBannerClickable === false ? button.onClick : null}

2 Answers 2

2

I would personally write it like this:

onClick={isBannerClickable ? null : button.onClick }

which is only different from yours in a few small ways:

  1. !!isBannerClickable will always be a boolean, true or false, so there's no need to === compare it to false. You can just negate it - or remove one of your negations. So here it would become !isBannerClickable.

  2. Then I've remove the ! and swapped round the 2 remaining clauses. This is obviously exactly the same, and is more of a personal choice, but I always much prefer in if/else or ternaries to have the "positive" condition first.

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

Comments

1

One way if isBannerClickable is not update frequently then you can use like this.

{ isBannerClickable ? <button onClick={onClickHandler}></button> : <button></button> }

But when the component in which the button is mount if reevaluates it will attach new onClick handler everytime.

Comments

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.