Skip to content

Instantly share code, notes, and snippets.

@roman01la
Last active March 16, 2016 04:43
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save roman01la/ca29d6e2ad80a6a92864 to your computer and use it in GitHub Desktop.
Save roman01la/ca29d6e2ad80a6a92864 to your computer and use it in GitHub Desktop.
class Nav extends React.Component {
constructor() {
super();
this.onNav = this.onNav.bind(this);
}
onNav(idx) {
// do something with `this` and `idx`
}
render() {
return (
<ul>
{btns.map((btn, i) => <Button key={btn} onClick={this.onNav} idx={i}>{btn}</Button>)}
</ul>
);
}
}
class Button extends React.Component {
shouldComponentUpdate(nextProps) {
return !shallowEqual(nextProps, this.props);
}
render() {
const { onClick, idx, children } = this.props;
return <button onClick={() => onClick(idx)}>{children}</button>;
}
}
@adam-beck
Copy link

Could you do something like:

onNav(idx) {
  return function() {
   // do something with `this` and `idx`
  };
}


....


{btns.map((btn, i) => <Button key={btn} onClick={this.onNav(i)}>{btn}</Button>)}

And that way you don't need to pass idx to the <Button> component?

@hccampos
Copy link

hccampos commented Feb 8, 2016

Nope, that won't work because `onNav()`` is returning a new function on every call anyway.

@adam-beck
Copy link

@hccampos is this what the author means by don't partially apply when passing them to components?

@adaniliuk
Copy link

@roman01la eslint with enabled jsx-no-bind rule does not allow syntax at line 24 as well:
return <button onClick={() => onClick(idx)}>{children}</button>;

Is it ok in such cases?

@adam-beck
Copy link

@adaniliuk I believe so in this case. You aren't creating a new function.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment