how to bind call component in react js code example

Example 1: react bind function to component

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>;
  }
}

Example 2: react call bind apply

.bind() is used to call a function with a given context. Using .bind() won’t call the function, only modifies the context.

.call() and .apply() will call the function immediately and modifies the context. The difference between the two:

.call() accepts a list of values as its arguments
.apply() accepts an array as its arguments
Use .bind() when you want to modify the context but you want to call the function later.

Use .call() or .apply() when you want to modify the context and you want to call the function immediately.