TGH
TGH

Reputation: 39248

Pass argument to reactjs click handler

I have a question about passing arguments to React click handlers. I have the following code, but for some reason the node argument is not passed to the toggle function. Shouldn't it? It's defined this way because it's a recursive component.

var Element = React.createClass({

    toggle: function(e,node){

    },

    render: function(){

        var nodes = this.props.children.map(function(n){

                return <Element node={n} text={n.text} children={n.children}  />

        });

        return (
               <span onClick={this.toggle.bind(this,this.props.node)}>{this.props.text}</span>

        );
    }

});

Upvotes: 18

Views: 18779

Answers (2)

bir_ham
bir_ham

Reputation: 513

While the above answer is correct. Here is another example how to pass both event and parameter to onClick function.

Your event firing element e.g a button:

<button onClick={this.editTask.bind(this, item._id)}>
  Edit item
</button>

Event handler function:

editItem(id, event) {
  event.preventDefault() // Prevents default form submission
  console.log('id: ', id) // Prints the item id 
  .
  .
  .
}

Upvotes: 0

Daniel Baulig
Daniel Baulig

Reputation: 10989

Function.prototype.bind bind arguments beginning from left. The correct way to receive the node argument is to look for it at the very left position of the argument list:

toggle: function(node, event) {
  console.log('node', node);
  console.log('event', event);
}

See http://jsfiddle.net/8xxfgce7/ for an example.

Upvotes: 23

Related Questions