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!

--

--

Nikola Đuza

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