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