Sandy Sandy - 2 months ago 13
React JSX Question

hide element on certain state in react.js

I don't know how to describe the title, forgive me. But I'm seriously stuck on something. I'm practicing a todo list where u can do inline editing. I'm stuck at hiding control buttons : edit and delete for a particular row when the state of isEdit for a particular row is present.

http://jsfiddle.net/rsp61fmh/

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

return(
<div className="itemCtrlWrap">
<button onClick={this.editHandler.bind(this,index)}>Edit</button>
<button onClick={this.dltHandler.bind(this, index)}>Delete</button>
</div>
)

},
editHandler(i){
this.setState({isEdit:i})
},
saveHandler(){
this.setState({isEdit:null})
},
dltHandler(index){
this.setState({items: this.state.items.filter((item,i) => i !== index)})
},
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

Adding condition to your ItemCtrl method like this may help :

   ItemCtrl(index){

   return index !== this.state.isEdit ? (
     <div className="itemCtrlWrap">
      <button onClick={this.editHandler.bind(this,index)}>Edit</button>
      <button onClick={this.dltHandler.bind(this, index)}>Delete</button>
   </div>
   ) : '';  
   },