Skip to content

Commit

Permalink
Fix indentation of example, and add a protip about ES6 classes.
Browse files Browse the repository at this point in the history
  • Loading branch information
Daniel15 committed Oct 28, 2015
1 parent 19faaac commit 752454b
Showing 1 changed file with 33 additions and 6 deletions.
39 changes: 33 additions & 6 deletions docs/rules/jsx-no-bind.md
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
# No `.bind()` or arrow functions in JSX props
# No `.bind()` or Arrow Functions in JSX Props

A `bind` call or [arrow function](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions) in a JSX prop will create a brand new function on every single render. This is bad for performance, as it will result in the garbage collector being invoked way more than is necessary.

Expand All @@ -18,7 +18,9 @@ The following patterns are not considered warnings:
<div onClick={this._handleClick}></div>
```

## Protip
## Protips

### Lists of Items

A common use case of `bind` in render is when rendering a list, to have a separate callback per list item:

Expand Down Expand Up @@ -56,9 +58,9 @@ var List = React.createClass({
var ListItem = React.createClass({
render() {
return (
<li onClick={this._onClick}>
...
</li>
<li onClick={this._onClick}>
...
</li>
);
},
_onClick() {
Expand All @@ -69,6 +71,31 @@ var ListItem = React.createClass({

This will speed up rendering, as it avoids the need to create new functions (through `bind` calls) on every render.

### ES6 Classes

Unfortunately [React ES6 classes](https://facebook.github.io/react/blog/2015/01/27/react-v0.13.0-beta-1.html#es6-classes) do not autobind their methods like components created with the older `React.createClass` syntax. There are several approaches to binding methods for ES6 classes. A basic approach is to just manually bind the methods in the constructor:

```js
class Foo extends React.Component {
constructor() {
super();
this._onClick = this._onClick.bind(this);
}
render() {
return (
<div onClick={this._onClick}>
Hello!
</div>
);
}
_onClick() {
// Do whatever you like, referencing "this" as appropriate
}
}
```

A more sophisticated approach would be to use something like an [autobind ES7 decorator](https://www.npmjs.com/package/core-decorators#autobind) or [property initializers](https://facebook.github.io/react/blog/2015/01/27/react-v0.13.0-beta-1.html#autobinding).

## When Not To Use It

If you do not want to enforce that `bind` or arrow functions are not used in props, then you can disable this rule.
If you do not use JSX or do not want to enforce that `bind` or arrow functions are not used in props, then you can disable this rule.

0 comments on commit 752454b

Please sign in to comment.