Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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>

        );
    }

});
like image 723
TGH Avatar asked Mar 21 '15 21:03

TGH


People also ask

How do you pass arguments to an event handler in react?

Passing the event object of react as the second argument. If you want to pass a parameter to the click event handler you need to make use of the arrow function or bind the function. If you pass the argument directly the onClick function would be called automatically even before pressing the button.

How do you get onClick value in react?

We set the onClick prop on the button element. Every time the button is clicked, the handleClick function is invoked. To get the value of the input field on button click, we simply access the message state variable in our handleClick function.

How do you pass onClick as props in react?

When you add an onClick prop to the LinkButton component, it is just a property of an object. By calling props. onClick from inside of that component you are just calling a function that is stored inside of a property, similar to this: let props = { onClick: function () { alert("Executed!"); } }; props.


1 Answers

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.

like image 85
Daniel Baulig Avatar answered Oct 06 '22 00:10

Daniel Baulig