Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

onClick event fired before clicking in react [duplicate]

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'));
like image 409
Sandy Avatar asked Dec 14 '22 03:12

Sandy


2 Answers

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.

like image 188
sospedra Avatar answered Dec 16 '22 15:12

sospedra


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.

like image 23
erik-sn Avatar answered Dec 16 '22 17:12

erik-sn