Andean Andean - 2 months ago 6
React JSX Question

Strange state behavior in react.js in my case

http://jsfiddle.net/1erw4fba/5/

var App = React.createClass({
getInitialState(){
return {
items:[1,2,3],
isEditing:false
}
},
dlt_item(key){
var newItems = this.state.items.filter((item,i)=> i !== key)
this.setState({items:newItems,isEditing:false})
},
edit_handler(){
this.setState({isEditing:true})
},
isEditing_html(){
return(
<div>
<input type="text" />
<button>Save</button>
</div>
)
},
renderItem(){

return(

this.state.items.map(function(item,i) {

var temp = null;
if(this.state.isEditing){
temp = this.isEditing_html()
}else{
temp = <div onClick={this.edit_handler}><button>Edit</button>
<button onClick={this.dlt_item.bind(this,i)}>Delete</button></div>
}
return (<li key={i}>{item}
&nbsp;
{temp}
</li>

)
}.bind(this)
)
)
},
render(){
return(
<ul>
{this.renderItem()}
</ul>
)
}
})


When I click delete button, why the edit input text appear? suppose it will only appear if the state of isEditing is true. Then I try to purposely set that to false, but still it appear. This is unusual to me.

Answer

Your problem is here:

temp = <div onClick={this.edit_handler}><button>Edit</button>
<button onClick={this.dlt_item.bind(this,i)}>Delete</button></div>

You put the onClick in the div, so it's called both when you press the Edit button or the Delete button. Just use:

 temp = <div><button onClick={this.edit_handler}>Edit</button>
 <button onClick={this.dlt_item.bind(this,i)}>Delete</button></div>