Sandy Sandy - 2 months ago 6
React JSX Question

onClick event fired before clicking in react

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'));

Answer

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.