Bomber
Bomber

Reputation: 10977

onClick not firing click handler

My click handler doesn't fire:

submitForm(UserDetails) {
    axios
        .post('http://localhost:3001/api/users', UserDetails)
        .then(function(response) {
            console.log(response);
        })
        .catch(function(error) {
            console.log(error);
        });
} 

ON my button:

<button
            className="btn btn-primary"
            onClick={this.submitForm(this.props.UserDetails)}>
            Upload
        </button>

I have bound it to this, in my constructor:

constructor() {
    super();
    this.submitForm = this.submitForm.bind(this);
}

Any ideas?

Upvotes: 0

Views: 67

Answers (1)

Karim
Karim

Reputation: 8652

In the onClick hook you're invoking the function instead of passing a reference of the function

<button
  className="btn btn-primary"
  onClick={this.submitForm(this.props.UserDetails)}>
  Upload
</button>

remove the bind from the constructor

this.submitForm = this.submitForm.bind(this);

and pass a proper function to the onClick

<button
  className="btn btn-primary"
  onClick={(e) => this.submitForm(this.props.UserDetails)}>
  Upload
</button>

Upvotes: 1

Related Questions