I think I missed something but don't know what is it, I know value={this.text} will bind the state's value, but since this is inline editing, I want to fill the input field with its existing value instead of blank.
http://jsbin.com/fugowebovi/1/edit
class TodoItem extends React.Component {
constructor(){
super()
this.state = {
text: '',
isEditing: false
};
this.onClickEdit = this.onClickEdit.bind(this);
this.onSaveEdit = this.onSaveEdit.bind(this);
this.onTextChanged = this.onTextChanged.bind(this);
}
onClickEdit(){
this.setState({isEditing: !this.state.isEditing});
}
onSaveEdit(){
this.setState({
text: this.state.text,
isEditing: false
});
}
onTextChanged(e){
this.setState({text: e.target.value});
}
render(){
return(
<li>
{this.state.isEditing ? '' : <span>{this.props.item}</span>}
{this.state.isEditing ? <span><input value={this.props.item} type="text" onChange={this.onTextChanged}/></span> :''}
{this.state.isEditing ? '' : <button onClick={this.onClickEdit}>Edit</button>}
<button onClick={this.onSaveEdit}>Save</button>
</li>
)
}
}
now the problem is it blocked the keypress.
Change <input value={this.props.item} type="text" onChange={this.onTextChanged}/>
to
<input value={this.state.text} type="text" onChange={this.onTextChanged}/>
As you are building a controlled component, you should provide it with its current text as value. See Controlled component in the docs
You use the value of props and change the value of the local state. That is why the input value is not changed
Try this:
class TodoItem extends React.Component {
constructor(props){
super()
this.state = {
text: props.item,
isEditing: false
};
this.onClickEdit = this.onClickEdit.bind(this);
this.onSaveEdit = this.onSaveEdit.bind(this);
this.onTextChanged = this.onTextChanged.bind(this);
}
onClickEdit(){
this.setState({isEditing: !this.state.isEditing});
}
onSaveEdit(){
this.setState({
isEditing: false
});
}
onTextChanged(e){
this.setState({text: e.target.value});
}
render(){
return(
<li>
{this.state.isEditing ? '' : <span>{this.state.text}</span>}
{this.state.isEditing ? <span><input value={this.state.text} type="text" onChange={this.onTextChanged}/></span> :''}
{this.state.isEditing ? '' : <button onClick={this.onClickEdit}>Edit</button>}
<button onClick={this.onSaveEdit}>Save</button>
</li>
)
}
}