Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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(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?

like image 253
Stralos Avatar asked Nov 21 '15 17:11

Stralos


People also ask

Why is onClick getting called on render?

Passing someFunctionName() is not a function or a reference to a function. It is a function call, meaning you are executing the someFunctionName function inside the onClick argument. That's the reason why your function passed to onClick event is executed immediately on page render.

Does onClick trigger render?

Even just putting a single div with an onClick attribute in its place doesn't work, the onClick still gets triggered when the component gets rendered, twice for each onClick.

Can you call multiple functions onClick React?

The first solution to perform multiple onClick events in React is to include all of your actions inside of a function and then call that single function from the onClick event handler. Let's explore how to do that in a React Component: import React from 'react'; function App() { function greeting() { console.


2 Answers

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.

like image 54
Long Nguyen Avatar answered Sep 20 '22 15:09

Long Nguyen


Instead of calling the function, bind the value to the function:

this.props.removeTaskFunction.bind(this, todo) 

MDN ref: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_objects/Function/bind

like image 45
Pete TNT Avatar answered Sep 20 '22 15:09

Pete TNT