reactjs 'this' context in a es6 class

- 1 answer

Ad

The es6 way of doing ReactJS is confusing with the context of 'this' keyword in a method inside a class

this gives an error cannot get refs of undefined

class AddItem extends React.Component {
    constructor() {
        super();
    }
    addIt(e) {
        e.preventDefault();
        let newItem = {
            title: this.refs.title.value
        }
        this.refs.feedForm.reset();
        this.props.addItem(newItem);
    }
    render() {
        return (
            <div>
              <form ref="feedForm" onSubmit={this.addIt}>
                <div className="input-group">
                  <span className="input-group-addon"><strong>Title:</strong></span>
                  <input ref="title" type="text" className="form-control" />
                </div>
                <button className="btn btn-success btn-block">Add Item</button>
              </form>
            </div>
        );
    }
}

But this seems to work fine

class AddItem extends React.Component {
    constructor() {
        super();
        this.addIt = function(e) {
            e.preventDefault();

            let newItem = {
                title: this.refs.title.value
            }

            this.refs.feedForm.reset();
            this.props.addItem(newItem);
        }.bind(this)
    }

    render() {
        return (
            <div>
              <form ref="feedForm" onSubmit={this.addIt}>
                <div className="input-group">
                  <span className="input-group-addon"><strong>Title:</strong></span>
                  <input ref="title" type="text" className="form-control" />
                </div>
                <button className="btn btn-success btn-block">Add Item</button>
              </form>
            </div>
        );
    }
}

What am i doing wrong in the first one

Ad

Answer

Ad

When you use ES6 classes for creating React components you need manually bind this for event handlers,

class AddItem extends React.Component {
  constructor() {
    super();
  }

  addIt(e) {
     // other code
  }

  render() {
    return <div>
      <form ref="feedForm" onSubmit={this.addIt.bind(this)}>
        // other code
      </form>
    </div>
  }
}

or much better set this in constructor,

class AddItem extends React.Component {
  constructor() {
    super();
    this.addIt = this.addIt.bind(this);
  }
  // other code
}
Ad
source: stackoverflow.com
Ad