0

Here is my situation:

<button onClick={this.changeTimerStatus.bind(this)}>makeTimerCliccable</button> <button onClick={this.state.hasBeenFinished ? this.confirmHandler : (this.state.hasDest == false || this.state.hasDest == undefined ? this.takeTaskHandler : this.finishHandler)}> 

I have two buttons, but I'd like to have just the second one. Also, I'd like to execute this.changeTimerStatus.bind(this) (the function on the first button) together with this.confirmHandler or this.takeTaskHandler when they're running. How can I solve this?

0

2 Answers 2

1

This should do it for you. Also here is a sandbox so you can see it in action: https://codesandbox.io/s/hardcore-bassi-2lwbu

 <button onClick={ this.state.hasBeenFinished ? () => { this.changeTimerStatus(); this.confirmHandler(); } : !this.state.hasDest ? () => { this.changeTimerStatus(); this.takeTaskHandler(); } : this.finishHandler } > Click </button> 

As fellow posters have mentioned, you can move all this logic into a single event-handler like so and pair it with the event-listener

handleClick = () => { this.state.hasBeenFinished ? () => { this.changeTimerStatus(); this.confirmHandler(); } : !this.state.hasDest ? () => { this.changeTimerStatus(); this.takeTaskHandler(); } : this.finishHandler } 

Then in the button:

<button onClick={this.handleClick}>Click</button> 

The benefits of doing this are:

  1. Prevents unnecessary re-renders caused by using anonymous functions as event-handlers during render.
  2. Cleans up your mark-up so its easier to read the logic behind your component.
Sign up to request clarification or add additional context in comments.

2 Comments

you can replace this.state.hasDest == false || this.state.hasDest == undefined by !this.state.hasDest
not good practice (avoid new function ref creation in render - forces unnecessary rerendering), not optimal (logic calculation on every render vs only one calculation on demand - within binded handler)
0

The answer that is accepted here will work, but that is not a good practice to use any logic inside your markup (in this case jsx). I would suggest to create one handler,

class YourComponent extends React.Component { state = { // Whatever you store in the state }; constructor(props) { super(props); this.clickHandler = this.clickHandler.bind(this); } clickHandler() { // this.state // ...logic can go here // it should be the same logic as it is in the accepted answer } render() { return ( <button type="button" onClick={ this.clickHandler }> BUTTON </button> ); } } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.