Skip to content

Commit 752454b

Browse files
committed
Fix indentation of example, and add a protip about ES6 classes.
1 parent 19faaac commit 752454b

File tree

1 file changed

+33
-6
lines changed

1 file changed

+33
-6
lines changed

docs/rules/jsx-no-bind.md

Lines changed: 33 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
# No `.bind()` or arrow functions in JSX props
1+
# No `.bind()` or Arrow Functions in JSX Props
22

33
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.
44

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

21-
## Protip
21+
## Protips
22+
23+
### Lists of Items
2224

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

@@ -56,9 +58,9 @@ var List = React.createClass({
5658
var ListItem = React.createClass({
5759
render() {
5860
return (
59-
<li onClick={this._onClick}>
60-
...
61-
</li>
61+
<li onClick={this._onClick}>
62+
...
63+
</li>
6264
);
6365
},
6466
_onClick() {
@@ -69,6 +71,31 @@ var ListItem = React.createClass({
6971

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

74+
### ES6 Classes
75+
76+
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:
77+
78+
```js
79+
class Foo extends React.Component {
80+
constructor() {
81+
super();
82+
this._onClick = this._onClick.bind(this);
83+
}
84+
render() {
85+
return (
86+
<div onClick={this._onClick}>
87+
Hello!
88+
</div>
89+
);
90+
}
91+
_onClick() {
92+
// Do whatever you like, referencing "this" as appropriate
93+
}
94+
}
95+
```
96+
97+
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).
98+
7299
## When Not To Use It
73100

74-
If you do not want to enforce that `bind` or arrow functions are not used in props, then you can disable this rule.
101+
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 commit comments

Comments
 (0)