1

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.

1 Answer 1

1

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>
Sign up to request clarification or add additional context in comments.

4 Comments

thanks for answer , but how do i then pass both functions to 1 onClick?
@NikitaVoevodin I've updated. basically just define a new function calling both add and somefunc.
got it. i was trying this before but it was telling me that add() and somefunc() were undefined . So, doing const add =()=>() instead of add(){} fixes that? Correct?
@NikitaVoevodin yes or bind the functions in the constructor as suggested.

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.