Sandy Sandy - 2 months ago 10
React JSX Question

this.refs.something.value return undefined in react

Click edit and then there will be an input bar appears, I expect when I click the save button, I can get the user's input but why I got undefined? There's no error in the console.

http://jsfiddle.net/2onzybk6/2

var App = React.createClass({
getInitialState() {
return {
items : [1, 2, 3],
isEdit: null
};
},
renderEditForm() {
return (
<div>
<input type="text" ref="newItem" />
<button onClick={ this.saveHandler }>Save</button>
</div>
);
},

ItemCtrl(index) {
if (index != this.state.isEdit) {
return (
<div className="itemCtrlWrap">
<button onClick={ this.editHandler.bind(this, index) }>Edit</button>
</div>
);
}
},
editHandler(i) {
this.setState({ isEdit: i });
},
saveHandler() {

console.log(this.refs.newItem.value); // why is this undefined?
this.setState({ isEdit: null });
},

renderItem() {
return (
this.state.items.map((item, i) =>
<li key={ i }> {this.state.isEdit == i ? this.renderEditForm() : item} {this.ItemCtrl(i)}</li>)
);
},
render() {
return (
<ul>
{this.renderItem()}
</ul>
);
}
});

Answer

The version of React you are using requires you to do this:

this.refs.newItem.getDOMNode().value

In more recent versions when you do this.refs.newItem it would actually return the dom node but in the version you are using in this fiddle it returns a React component object. When you call getDOMNode() it will get the actual DOM element and then you can call regular DOM properties

Comments