mangesh
mangesh

Reputation: 521

onClick not working after defining multiple onClick events

I had an onClick event define which was working fine:

onClick={this.props.removeFunctionsData.bind(null,this.props.path,this.props.obj.data_type)}

Now I want to define two events on the same onClick. I tried doing this:

onClick={(e)=>{this._onClose(e);this.props.removeFunctionsData.bind(null,this.props.path,this.props.obj.data_type);}}

But in this case only this._onClose(e) works and not the original one. How can I fix this?

Upvotes: 0

Views: 214

Answers (2)

Dyo
Dyo

Reputation: 4464

Original answer :

You can execute your function by adding () at the end :

onClick={
  (e)=>{
    this._onClose(e);
    this.props.removeFunctionsData.bind(null,this.props.path,this.props.obj.data_type)();
  }
}

Edit : as dschu commented, the above code is pretty bad, binding or using arrow function in the render method is a bad practice because it creates a new function each time.

  • Binding your function is useless in this case because you pass null as first argument.
  • To solve the arrow function performance issue in a generic way you have to bind your function in the constructor or declare an arrow method.

Here's a better code to do what you need :

Class MyComponent extends React.Component {
  // your other class methods
  handleClick = (e) => {
    this._onClose(e);
    this.props.removeFunctionsData(this.props.path,this.props.obj.data_type);
  }
  render() {
    <div onClick={this.handleClick} />
  }
}

Upvotes: 0

dschu
dschu

Reputation: 5362

Inside your component, define a handleClick function, using the ES6 arrow function syntax. This syntax doesn't create a new context, therefore you don't have to bind this inside the constructor or when calling it.

Here's an example using the info I've got from your post

class Example extends React.Component {
    handleClick = () => this.props.removeFunctionsData(this.props.path, this.props.obj.data_type);

    render() {
        return (
            <ComponentToClick onClick={this.handleClick} />
        )
    }
}

Upvotes: 1

Related Questions