Search code examples
javascriptreactjsreactjs-flux

Any ideas why this react components buttons onClick would not be firing


I have the following component:

var React = require("react");

var CollectionsButtonActions = require("../actions/CollectionsButtonActions");


var CollectionsApp = React.createClass({
    getInitialState: function () {
        return {text: ''};
    },

    render: function () {
        var that = this;

        var buttonItem = <button
            onClick={this._handleButtonClick}
        >Test</button>;

        return (
            <div className="view">
                <div className="anchor">
                {buttonItem}
                </div>
                <div className="main">
                    <p>You currently don't have any collections set up,
                        <a href="/admin/collections/new">create one</a>
                        .</p>
                    <ul>
                    </ul>
                </div>
            </div>
        )
    },

    _handleButtonClick: function (event) {
        console.log('test');
        //CollectionsButtonActions.loadCollections();
    }
});

module.exports = CollectionsApp;

For some reason, the _handleButtonClick event is not firing at all, Iv'e tried various ways of including the button but for some reason this button just does not want to fire it's event. I can see the a similar example here https://github.com/facebook/flux/blob/master/examples/flux-todomvc/js/components/Footer.react.js#L48 in the Flux TodoMVC example application which seems to work but for some reason with the code above, the click event is not getting attached to the button.

Any ideas?


Solution

  • This turned out to be an issue with require being called with two different arguments for react within the overall application.

    For instance, in the bundle.js (entrypoint of the application) it was called like so:

    var React = require('./node_modules/react/dist/react-with-addons');
    

    But in the actual react component file it was being loaded with it's short name, like so:

    var React = require("react");
    

    I believe what's happening here is that require is treating the two as completely separate loads (as it should) and when the require("react") call is happening in one of the further down components it's wiping the original React events away set up further up the chain as the React library is being loaded twice. Because React uses its synthetic events, the events aren't in the DOM so when the React object is overwritten on the second load those events are lost.

    This is a silly human error, but easily made, hopefully this saves someone a little grief later on.