react icon indicating copy to clipboard operation
react copied to clipboard

'this' becomes undefined when called from onClick inside a class that extends React.Component

Open go1t opened this issue 11 years ago • 5 comments

I have something similar to this code snippet:

class MyButton extends Component {

    state = { tapped: false }
    tap() {
          this.setState({ tapped: true });  // --> 'this' here is undefined 
    }
    render() {
        return (
             <button onClick={ this.tap }>TAP ME</button>
        )
    }
}

As the comment above specifies, when the tap() method got called from the button's onclick, I got an error that basically told me that 'this' is undefined.

This error will be gone if I declare this class using React.createClass. Is this intentional? Thank you in advance!

go1t avatar Oct 02 '15 08:10 go1t

React.createClass auto bind this for you behind the scene.

In ES6 classes, you should bind this yourself: <button onClick={this.tap.bind(this)}>

chentsulin avatar Oct 02 '15 09:10 chentsulin

I see, thank you so much!

go1t avatar Oct 02 '15 09:10 go1t

Just for info, it can also be solved as below,

class MyButton extends Component {

    state = { tapped: false }
    tap = (e) => {
          this.setState({ tapped: true });
    }
    render() {
        return (
             <button onClick={ this.tap }>TAP ME</button>
        )
    }
}

arundhaj avatar Feb 02 '18 07:02 arundhaj

In my case, for a stateless component that received the ref with forwardRef, I had to do what it is said here https://itnext.io/reusing-the-ref-from-forwardref-with-react-hooks-4ce9df693dd

From this (onClick doesn't have access to the equivalent of 'this')

const Com = forwardRef((props, ref) => {
  return <input ref={ref} onClick={() => {console.log(ref.current} } />
})

To this (it works)

const useCombinedRefs = (...refs) => {
  const targetRef = React.useRef()

  useEffect(() => {
    refs.forEach(ref => {
      if (!ref) return

      if (typeof ref === 'function') ref(targetRef.current)
      else ref.current = targetRef.current
    })
  }, [refs])

  return targetRef
}

const Com = forwardRef((props, ref) => {
  const innerRef = useRef()
  const combinedRef = useCombinedRefs(ref, innerRef)

  return <input ref={combinedRef } onClick={() => {console.log(combinedRef .current} } />
})

kuworking avatar Jan 15 '20 06:01 kuworking

React.createClass auto bind this for you behind the scene.

In ES6 classes, you should bind this yourself: <button onClick={this.tap.bind(this)}>

Saved my A** thanks

abhiways avatar Oct 16 '21 16:10 abhiways