React: Binding Events

Table of Contents

Bind

We bind because of this keyword in JS.

Bind

/src/component/EventBind.js

import React, { Component } from 'react'

class EventBing extends Component {

    // rconst 
    constructor(props) {
      super(props)
    
      this.state = {
         message: 'Hello'
      }
    }
    
    clickHandler () {
        this.setState({
            message: "goodbye"
        })
    }

  render() {
    return (
      <div> 
        <div>{this.state.message}</div>
        {/* Adding `.bind(this)` */}
        <button onClick={this.clickHandler.bind(this)}>Clicks</button>
      </div>
    )
  }
}

export default EventBing

Arrow function

Most easy way

import React, { Component } from 'react'

class EventBing extends Component {

    // rconst 
    constructor(props) {
      super(props)
    
      this.state = {
         message: 'Hello'
      }
    }

    clickHandler = () => this.setState({message: "goodbye!!"})

  render() {
    return (
      <div> 
        <div>{this.state.message}</div>
        {/* Adding `.bind(this)` */}
        <button onClick={() => this.clickHandler()}>Clicks</button>
      </div>
    )
  }
}

export default EventBing

Bind in constructor

React recommended

import React, { Component } from 'react'

class EventBing extends Component {

    // rconst 
    constructor(props) {
      super(props)
    
      this.state = {
         message: 'Hello'
      }

      this.clickHandler = this.clickHandler.bind(this)

    }
    
    clickHandler () {
        this.setState({
            message: "goodbye"
        })
    }

  render() {
    return (
      <div> 
        <div>{this.state.message}</div>
        {/* Adding `.bind(this)` */}
        <button onClick={this.clickHandler}>Clicks</button>
      </div>
    )
  }
}

export default EventBing

Arrow as class property

React recommended

import React, { Component } from 'react'

class EventBing extends Component {

    // rconst 
    constructor(props) {
      super(props)
    
      this.state = {
         message: 'Hello'
      }
    }
    
    clickHandler = () => {
        this.setState({
            message: "goodbye"
        })
    }

  render() {
    return (
      <div> 
        <div>{this.state.message}</div>
        {/* Adding `.bind(this)` */}
        <button onClick={this.clickHandler}>Clicks</button>
      </div>
    )
  }
}

export default EventBing