Croolsby Croolsby - 1 year ago 55
React JSX Question

What is the difference between these two declarations in react javascript?

I am using the class syntax to declare a react component:

import React, {Component} from 'react'
class Page extends Component {
constructor(props) {
this.state = {value: ''}

doA(event) {this.setState({value:})}

doB = (event) => {this.setState({value:})}

render {
return (
<input type="text" onChange={this.doB}/>

{*the following is wrong:*}
{*<input type="text" onChange={this.doA}/>*}

If I try to handle
, I get this error:
TypeError: Cannot read property 'setState' of undefined

's declaration looks more like a class method from Java, and
's declaration looks more like an anonymous function assigned to a class property. I would have thought using
onChange = this.doA
would keep
assigned to the class, but it's the other way around.
onChange = doB
assigned to the class.

I tried searching for explanations but I don't know the proper terminology, thus my search terms are poor.

On a side note: If I use
onChange = doA
, I get that error, but the input field will still update correctly. So
is changing, yet it's giving me that error. Why is that?

Answer Source

Arrow functions in JavaScript lexically bind this for you. That's the reason doB works properly while doA doesn't.

If you bind doA in the constructor, things will work as expected using class syntax:

constructor(props) {
    this.doA = this.doA.bind(this);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download