Friday, May 17, 2024
 Popular · Latest · Hot · Upcoming
53
rated 0 times [  60] [ 7]  / answers: 1 / hits: 195545  / 9 Years ago, sat, november 21, 2015, 12:00:00

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(it should not fire on render time). My code looks like this:



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


My question is: why does onClick function fire on render and how to make it not to?


More From » reactjs

 Answers
27

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



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


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


[#64317] Thursday, November 19, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
quentinaveryb

Total Points: 102
Total Questions: 100
Total Answers: 93

Location: Colombia
Member since Mon, May 2, 2022
2 Years ago
quentinaveryb questions
Thu, Aug 6, 20, 00:00, 4 Years ago
Fri, Jul 17, 20, 00:00, 4 Years ago
Mon, Aug 12, 19, 00:00, 5 Years ago
;