Jean-louis Gouwy Jean-louis Gouwy -4 years ago 123
Javascript Question

react/jsx-no-bind: how to pass args

I've some difficulties to understand jsx-no-bind when we've some args to pass in method.

My code works correctly :

class Foo extends React.Component {
foo(reverse, e) {
if(reverse) {
//smthg to do with e.target
} else {
//smthg to do with e.target
}
// call this.bar()
}

bar() {
//smthg
}

render() {
return (
<button type="button" onClick={this.foo.bind(this, false)}>go</button>
<button type="button" onClick={this.foo.bind(this, true)}>reverse</button>
);
}
}


But I've jsx-no-bind with my linter.

How can i use the right way with :

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


But ... in passing some args. In my case, I want to pass "reverse" argument.

thanks in advance,

Answer Source
constructor() {
  super();
  this.foo = this.foo.bind(this);
}

This should work just fine. Later when you call this.foo( true ) or this.foo( false ), the function will be correctly bound to the instance.

Depending on your transpiler/stack you can make use of arrow functions to make it even quicker:

class Foo extends React.Component {
  foo = ( reverse, e ) => {
    // ...
  }
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download