Search code examples
javascriptreactjsonclickbind

How to bind two functions to a button click in React


I am trying to bind 2 functions to the same onClick event in the reactjs button.

I saw a few examples here but they did not work for me; either the syntax is different or my code logic just won't support two functions inside one button click. Here is an example of what I'm doing:

class Example extends Component {
    state = {
        test:1
    }

    //function 1
    add() {
        this.setState({
            test: this.state.test+1
        });
    }

    //function 2
    somefunc() {
        // does smthng
    }

    render() {
        return (
            <div>
                <Button color = 'success' 
                    onClick={this.add.bind(this)}>+1
                </Button>
            </div>
        )
    }
}

The code above works. But I need to be able to add the second (somefunc()) function to that onClick. Something like this:

onClick={() => {this.add.bind(this); this.somefunc.bind(this)}}

Is it possible with bind? If not, could you please explain how to call a function without the bind.


Solution

  • Bind the functions in the constructor.

    constructor (props) {
      super(props);
      this.add = this.add.bind(this);
      this.somefunc = this.somefunc.bind(this);
    }
    

    Or use arrow notation (no need for bind)

    const add = () => { /* do something */ }
    const somefunc = () => { /* do something */ }
    
    <Button 
      onClick={this.add}
    >
      +1
    </Button>
    

    UPDATE

    Using both functions in one onClick

    const doSomething = (e) => {
      add();
      somefunc();
    }
    
    <Button 
      onClick={this.doSomething}
    >
      +1
    </Button>