Skip to content Skip to sidebar Skip to footer

React Js Onclick Inside Render

I have a ul li list inside the render method and there is an onClick event on li which call this.handleClick function and state gets changed var InspirationFilter = React.createCla

Solution 1:

The problem is that onClick value has to be a function, so just create a helper method that creates such a function for you:

createClickHandler: function(filter, filterText){
    returnfunction() {
        this.setState({...});
    }.bind(this);
},

render: function() {
    return (
        <ul><lionClick={this.createClickHandler('top_all_time', 'TopAllTime')}>Top All Time</li><lionClick={this.createClickHandler('top_this_week', 'TopThisWeek')}>Top Week</li><lionClick={this.createClickHandler('top_this_month', 'TopThisMonth')}>Top Month</li></ul>
    );
}

React is really just a bit over-helpful here with its warning. Your reason for using bind() is no to bind this, but rather to bind the arguments.

Why it works? This solution avoids the re-binding warning because it's not re-binding an already bound this.handleClick, but instead creating a new function (that's not yet bound to anything) and binding that.

Solution 2:

To summarize, in your first example, when you use this format:

onClick={this.functionName(arg1, arg2)

you are calling the functions rather than providing a reference to the functions. Hence they are being called directly every time it is being rendered rather than onClick as intended.

When you use the format:

onClick={this.functionName.bind(this, arg1, arg2)}

you are providing a reference to the function and binding context and arguments, rather than calling it. This is the correct method; ignore the warnings (even though there are way too many and it's really annoying)

Solution 3:

Yes, you do need to pass a function to onClick.

You have a typo on the third <li>

return (
    <ul>
        <li onClick={this.handleClick.bind(this,'top_all_time', 'Top All Time')}>Top All Time</li>
        <li onClick={this.handleClick.bind(this,'top_this_week', 'Top This Week')}>Top  Week</li>
        <li onClick={this.handleClick.bind(this, 'top_this_month', 'Top This Month')}>Top  Month</li>
    </ul>
);

Check this Fiddle https://jsfiddle.net/69z2wepo/20047/ It works on React 0.14

Post a Comment for "React Js Onclick Inside Render"