Events

Objectives

  • Demonstrate an onClick event

  • Using bond functions vs inline callbacks

onClick

class ClickExample extends Component {
  constructor(props) {
    super(props);
    this.state = { name: "tim" };
  }
  render() {
    return (
      <div>
        <p>{this.state.name}</p>
        <button type="button"
          onClick={() => this.setState({name: "TIM"})}>
          UPPERCASE
        </button>
      </div>
    );
  }
}
class ClickExample extends Component {
  constructor(props) {
    super(props);
    this.state = { name: "tim" };
    this.handleClick = this.handleClick.bind(this);
  }
  handleClick(e) {
    this.setState((prevState, props) => ({
      name: prevState.name.toUpperCase()
    });
  }
  render() {
    return (
      <div>
        <p>{this.state.name}</p>
        <button type="button" onClick={this.handleClick}>
          UPPERCASE
        </button>
      </div>
    );
  }
}
render() {
  return (
    <div>
      <p>{this.state.name}</p>
      <button type="button" onClick={this.handleClick()}>
        UPPERCASE
      </button>
    </div>
  );
}

Common Mistake

The function will be invoked immediatley, not on the event

In Line Arrow Functions vs Bind

No noticeable performance benefits of using bind in the constructor