I want to remove the li whenever user click the delete button. So I pass the index around but it got triggered before I click on it, I guess I'm doing it wrong for passing the value.
http://jsfiddle.net/axhpuepq
var App = React.createClass({
   getInitialState(){
     return {
       items:[1,2,3],
       isEdit: false
     }
   },
   renderEditForm(){
   return(
   <div>
   <input type="text" />
   <button onClick={this.saveHandler}>save</button>
   </div>
   )
   },
   ItemCtrl(index){
   return(
   <div className="itemCtrlWrap">
   <button onClick={this.editHandler}>Edit</button>
   <button onClick={this.dltHandler(index)}>Delete</button>
   </div>
   )
   },
   editHandler(){
   this.setState({isEdit:true})
   },
   saveHandler(){
    this.setState({isEdit:false})
   },
   dltHandler(index){
     console.log(index) //shall recieve index here upon click
   },
   renderItem(){
     return(
       this.state.items.map((item,i)=>
         <li key={i}> {this.state.isEdit ? this.renderEditForm() : item} {this.ItemCtrl(i)}</li>)
     )
   },
   render(){
      return(
        <ul>
          {this.renderItem()}
        </ul>
      )
   }
})
React.render(<App />, document.getElementById('container'));
                You're executing the function instead of just setting it, here:
onClick={this.dltHandler(index)}
If you want to pass some arguments bind them. Like:
onClick={this.dltHandler.bind(this, index)}
or use an arrow function:
onClick={() => this.dltHandler(index)}
If you notice, we're setting a function while declaring it to onClick. And this function is just executing dltHandler. 
When you define the onClick like this it is calling that function on instantiation. You need to use bind or define an anonymous function:
   <button onClick={this.dltHandler.bind(this, index)}>Delete</button>
or
   <button onClick={() => this.dltHandler(index)}>Delete</button>
Both of these pass a function to the onClick handler - but they do not execute until onClick is fired. Note that doing this will cause a new function to be generated on every render call. This can be expensive computationally if you are rendering very often.
If performance becomes an issue it is a better solution to refactor the button into a separate component that has a defined dltHandler function.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With