Binding

The JavaScript bind method has several uses. Typically, it is used to preserve execution context for a function that executes in another context.


How do I bind events (i.e. onClick) in React?

There are several ways to bind things in React this video via Kent C. Dodds + @eggheadio covers multiple ways to bind events showing the benefits and drawbacks for each.

⭐ React FAQ -> use public class fields

//see demo: https://jsbin.com/suzubu/1/edit?html,js,output
class App extends React.Component {
  state = {clicks: 6}

  handleClick = (e) => {
    console.log(e.target.dataset.id)
    this.setState(prevState => {
      return {clicks: prevState.clicks + 1}
    })
  }

  render() {
    return (
      <div>
        <div>
          Click Count: {this.state.clicks}
        </div>
        <button data-id={1}
          onClick={this.handleClick}
        >
          Click Me!
        </button>
      </div>
    )
  }
}

What should you use for binding methods in React classes?

What is this bind thing?