Cory House:
There are at least five ways to handle the this context in React. Let’s consider the merits of each approach.
- Use
React.createClass
- Bind in Render
- Use Arrow Function in Render
- Bind in Constructor
- Use Arrow Function in Class Property
Currently I’m mostly using Approach 4 (“Bind in Constructor”), but Approach 5 (“Arrow Function in Class Property”) looks like something to switch to after having read the post.
React Binding Patterns: 5 Approaches for Handling this
→
On a sidenote, ES2017+ will sport the Function Bind Operator (::
) which acts a a shorthand for .bind(context)
.
// ES2015
this.logMessage = this.logMessage.bind(this);
// ES2017
this.logMessage = ::this.logMessage;