0
class Foo extends Component {
  constructor(props) {
    super(props);
    this.handleClick = this.handleClick.bind(this);
  }
  handleClick() {
    console.log('Click happened');
  }
  render() {
    return <button onClick={this.handleClick}>Click Me</button>;
  }
}

i tried to remove this code

this.handleClick = this.handleClick.bind(this);

but there's no problem, still works. Can you give me some examples that illustrate of what bind does in reactjs context (like in the first code), like if you remove this bind code, will results in error

Drf
  • 57
  • 4
  • 1
    Your handler never uses `this`, so it works whether you bind `this` or not. That's about it. If it used the specific instance, you would need to bind that. – underscore_d Jul 17 '20 at 11:24
  • can you give example that uses this that similar to my code? so i can know which work and which result will error – Drf Jul 17 '20 at 11:40
  • Just try with the `bind(this)` removed and something in your `handleClick()` body that tries to use `this`, and you'll see that it doesn't work without `this` being bound to the handler. – underscore_d Jul 17 '20 at 11:42
  • Create a state variable and try to log it as @underscore_d suggested. `console.log(this.state.foo)` – devserkan Jul 17 '20 at 11:48

1 Answers1

2

bind() is a JS function that sets this to the context provided.

You are actually not using this in your example, so it doesn't matter.

It's also worth noting that the arrow function () => {} is equivalent to calling bind(), so for example if you were to declare your click handler as:

handleClick = () => {
  console.log('Click happened');
}

It would set this to the value you expect.

Simone
  • 20,302
  • 14
  • 79
  • 103