Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Infinite loop in React button

This simple React button class triggers an infinite loop on click (i.e. logging 'click!' to the console 100s of times):

///////////////////////////////////////////////////////////////////////////////////////////
// TestButton.js

exports.TestButton = React.createClass({

    onClick: function(event) {
        event.preventDefault();
        event.stopPropagation();
        console.log('Click!')
    },

    render() {
        return (
            <div>
                <button type="button" onClick={this.onClick}>Click me!</button>
            </div>
        )
    }
});


///////////////////////////////////////////////////////////////////////////////////////////
// main.js

var TestButton = require('./TestButton.js').TestButton;

ReactDOM.render(
    <div>
        <TestButton/>
    </div>,
  document.getElementById('main')
);

The infinite loop is not triggered every time, but around every 10th time I load the page and click the button (in a non-repeatable manner). It's independent of the browser I use.

Any ideas where this is coming from?

I know this isn't repeatable in a JS-fiddle. The question is 'Where should I start to look in my setup for where this condition is coming from? Browserify? Imported scripts? React itself?'

like image 586
AndreasWeller Avatar asked Oct 21 '15 10:10

AndreasWeller


1 Answers

I don't know if it'll help as your code part doesn't has any parameter but I had almost the same symptoms, the onclick callback function was called in a loop:

<Button onClick={this.close(id)}>
    Close
</Button>

I finally understood my mistake. A closure was expected while I was simply running the function... So, if the function doesn't take any parameter, we can just use onClick={this.close} but otherwise, in ES6, we need to use arrow functions to simply pass the function:

<Button onClick={() => this.close(id)}>
    Close
</Button>

onClick the anonymous function is called and executes this.close(id)

like image 142
lenybernard Avatar answered Nov 08 '22 05:11

lenybernard