Stralos Stralos - 1 year ago 324
Javascript Question

React onClick function fires on render

I pass 2 values to a child component:

  1. List of objects to display

  2. delete function.

I use a .map() function to display my list of objects(like in the example given in react tutorial page), but the button in that component fires the onClick function, on render(in should not fire on render time). My code looks like this:

module.exports = React.createClass({
render: function(){
var taskNodes ={
return (
<button type="submit" onClick={this.props.removeTaskFunction(todo)}>Submit</button>
}, this);
return (
<div className="todo-task-list">

My question is: Why does mine onClick function fire on render and how to make it not to.

Answer Source

Because you are calling that function instead of passing function to onClick, change that line to this:

<button type="submit" onClick={() => { this.props.removeTaskFunction(todo) }}>Submit</button>

=> called Arrow Function, which was introduced on ES6, and will be supported on React 0.13.3 or upper.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download