Why .bind() needed in ReactJS?
While working on React, every developer must have come across controlled components and used bind method in constructors.
For Example:
What it does?
Many developers don't know about it thoroughly. In this article, I'll share my knowledge about it.
Firstly, .bind() is a method of javascript not ReactJS. In above example, this.handleClick.bind(this) function is binding the key this to the function in the context of the React Component. It means is that whenever it tries to access a property of the React Component, React can access it like this.props since this will then refer to the React Component's context and not the function itself.
What happens if you do not use it?
It is crucial to know, what will happen if you don't use it. By doing that, you can learn more about that function what it is actually does at the core.
When you call that functionhandleClick(), and tries to console the this keyword in it, you get undefined printed to the console as the value of this from inside the event handler method. That is because of it looses it's context from react component.
Hope above explanation helps you. I know this is a complex concept but there are new ways to avoid using bind() method. You can follow below tutorials for it.