Skip to content

replace this.function.bind(this) for function component

I have a class component that looks like this:

interface MyProps {
  addingCoord: any
  resetCoords: any
}

interface MyState {
  x: any
  y: any
}

class DrawerOld extends React.Component<MyProps, MyState> {
  width: number
  height: number

  constructor(props: MyProps) {
    super(props)
    this.state = {x: NaN, y: NaN, hoverMode: false}
    this.width = this.height = 400
  }

  onMouseMove(e: React.MouseEvent<HTMLDivElement, MouseEvent>) {
    this.setState(
      {
        x: parseFloat((e.nativeEvent.offsetX / this.width).toFixed(3)),
        y: parseFloat(
          ((this.height - e.nativeEvent.offsetY) / this.height).toFixed(3),
        ),
      },
      () => {
        if (this.state.hoverMode) this.addCoord()
      },
    )
  }

  toggleHoverMode() {
    this.setState({hoverMode: !this.state.hoverMode})
  }

  addingCoord() {
    const coord = {x: this.state.x, y: this.state.y}
    this.props.addingCoord(coord)
  }

  render() {
    return (
      <div>
        <div>
          <div
            onMouseMove={(e) => this.onMouseMove(e)}
            onClick={this.addCoording.bind(this)}
          />
        </div>
      </div>
    )
  }
}

export default DrawerOld

I want to modify it into a functional component. However, I am unable to figure out how to accurately modify this part: onClick={this.addCoord.bind(this)}

because currently if I use onClick={props.addCoord()}, I would get errors like these upon using it:

TypeError: Cannot read property ‘x’ of undefined

<DrawerNew addCoord={this.addCoord.bind(this)}
                            resetCoords={this.resetCoords.bind(this)} />

Answer

Change your onClick

from this

onClick={props.addCoord()}

to this

onClick={addCoord}