Losing .bind(this) in React

Nikola Đuza
4 min readJan 13, 2018

Getting rid of .bind(this) in React component.

Photo by JANNIK SELZ on Unsplash

If you used React in your time, you probably had to write some of .bind(this) code. And yes, I know:

  • it looks pretty ugly, plus,
  • it’s taking up some extra space in the codebase.

Luckily, there are some proposed features of JavaScript that can make .bind(this) the past for us.

Before I explain how to lose .bind(this), I’ll show you a short example of where this can be used. Let’s say we want to render a button which changes its text when you click it. In order to do that, we would write a component similar to the one below 🔽.

We set the toggle switch in the state to false in our constructor.

Also, we add the toggleButton function as onClick handler function, so it will get called when the button is clicked.

And, we create a simple toggleButton function which toggles the state when called.

Awesome, seems like we’re good to go!

If we go ahead an click the rendered button, we’ll get a TypeError like this:

Dang it! It should work 🤔.

We’re getting an error because this is not defined when onClick calls our toggleButton function.

Usually, you would fix this by binding this to the toggleButton function so it always stays the same. Let’s go ahead and bind this to our function in the constructor with:

After adding it, our button component should look like this:

Nikola Đuza

Nikola helps developers improve their productivity by sharing pragmatic advice & applicable knowledge on JavaScript and Ruby. https://pragmaticpineapple.com/ 🍍