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.
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:
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: