Never bind your React methods again.

How often have you done the following when binding the this context when using React methods?

My favorite way of binding is by creating a base component class with a bind method which binds any methods passed to it and then extending the base class to my React components. A mouthful, right? Stay with me.

If you’re new to ES6/ES7, then let me explain what’s going on in the code. The …methods is the spread operator which allows us to pass multiple arguments to our method. From there we iterate over all the methods passed and use an arrow “=>” function which is just syntactic sugar for a typical callback or anonymous function in pre-ES6. Normally they’re written in the following manner:

Not only are arrow functions shorter and look better than writing function() but they also remember the scope in which they’re being used, so you no longer have to write hacky code anymore like var that = this in a higher scope and then using that within your callback(s) to refer to this context somewhere else in your code.

Back to the code: After we iterate over each method we then call the bind to ensure our this context is bound to our methods when we use them.

Lastly, to use the new method we just created we extend our MainComponent and in our constructor we use this.bind() and pass in the methods we want bound.

After binding in our constructor we no longer have to explicitly bind when we call the method. Hopefully this frees you up to focus on more important things in your app instead of chasing down why a method’s this returns null or is not working. Happy coding!

One clap, two clap, three clap, forty?

By clapping more or less, you can signal to us which stories really stand out.