Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add guidance on method binding for class components #7113

Merged
merged 3 commits into from
Jan 12, 2022
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 42 additions & 0 deletions STYLE.md
Original file line number Diff line number Diff line change
Expand Up @@ -511,6 +511,48 @@ const propTypes = {
}
```

## Binding methods

For class components, methods should be bound in the `constructor()` if passed directly as a prop or needing to be accessed via the component instance from outside of the component's execution context. Binding all methods in the constructor is unnecessary. Learn and understand how `this` works [here](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this).

```javascript
// Bad
class SomeComponent {
constructor(props) {
super(props);

this.myMethod = this.myMethod.bind(this);
}

myMethod() {...}

render() {
return (
// No need to bind this since arrow function is used
<Button onPress={() => this.myMethod()} />
);
}
}

// Good
class SomeComponent {
constructor(props) {
super(props);

this.myMethod = this.myMethod.bind(this);
}

myMethod() {...}

render() {
return (
// Passed directly to Button so this should be bound to the component
<Button onPress={this.myMethod} />
);
}
}
```

## Inline Ternarys
* Use inline ternary statements when rendering optional pieces of templates. Notice the white space and formatting of the ternary.

Expand Down