reactjs 'this' context in a es6 class
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
Related Questions
Ad
- → How to update data attribute on Ajax complete
- → October CMS - Radio Button Ajax Click Twice in a Row Causes Content to disappear
- → Octobercms Component Unique id (Twig & Javascript)
- → Passing a JS var from AJAX response to Twig
- → Laravel {!! Form::open() !!} doesn't work within AngularJS
- → DropzoneJS & Laravel - Output form validation errors
- → Import statement and Babel
- → Uncaught TypeError: Cannot read property '__SECRET_DOM_DO_NOT_USE_OR_YOU_WILL_BE_FIRED' of undefined
- → React-router: Passing props to children
- → ListView.DataSource looping data for React Native
- → Can't test submit handler in React component
- → React + Flux - How to avoid global variable
- → Webpack, React & Babel, not rendering DOM
Ad