0

I have a question. How I can unbind the click of element in react? I have button, when I click on it, it increases score + 1, and after this click I want to remove it. How I can do this?

Help me please!

class Toggle extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      result: 2,
      score: 0
    };
    
    this.getRes = this.getRes.bind(this);
  }
  

 
  
  getRes() {
    if (this.state.result == 2) {
      this.setState({score: this.state.score+1})
      
      this.getRes.unbind(this);
      
    }
  }

  render() {
    return (
      <div>
      <div style={{paddingTop: 10}}>
        <p>
        <button>1</button>
        <button onClick={this.getRes}>{this.state.result}</button>
        </p>
        
          <p>
        <button>1</button>
        <button onClick={this.getRes}>{this.state.result}</button>
        </p>
        
        
        <p>{this.state.score}</p>
        
        </div>
        </div>
    );
  }
}

ReactDOM.render(
  <Toggle />,
  document.getElementById('root')
);

3
  • don't unbind the event, just use state and logic to see if you have incremented yet, and if you already have, just make the function noop Commented Sep 19, 2019 at 17:06
  • 2
    when would this.state.score == this.state.score be false ? Commented Sep 19, 2019 at 17:06
  • If you don't want a click-handler on an element, then don't add a click-handler to that element. In React you do not mutate/change the DOM. You tell react how the (new) DOM should look like (either with or without click-handler) and let react take the necessary steps to get there. Commented Sep 19, 2019 at 17:07

1 Answer 1

4

In React, you change your UI by making render() describe the new state, not by manually binding or unbinding or changing things.

Change your render() method to only pass this.getRes to onClick if you want the handler to by bound:

onClick={... ? this.getRes : null}
Sign up to request clarification or add additional context in comments.

2 Comments

what to put instead 3 dots?
@rapprogtrainsite: Whatever condition you want.

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.