0

I'm unable to initiate a simple onClick event through reactjs with react.net in a MVC 5 View. The data binding and other functions I have written seem to work fine. I keep getting an error stating alert is undefined, but its just a simple javascript alert which doesn't make any sense. Please see my code below :

class ClickTest extends React.Component {
    ClickMe(){
        alert('the button was clicked');
    };
    render() {
        return (
            <div onClick={this.ClickMe()}>
                Click Me
          </div>
        );
    }
}

The code that is generated for my component is below :

// @hash v3-241CABCC1541735262CAFE84D809779D00FA7D7B
// Automatically generated by ReactJS.NET. Do not edit, your changes will be overridden.
// Version: 3.2.0 (build 0e1da66) with Babel 6.7.7
// Generated at: 2017/11/10 12:00:58 PM
///////////////////////////////////////////////////////////////////////////////
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

var HomeComp = function (_React$Component) {
    _inherits(HomeComp, _React$Component);

    function HomeComp() {
        var _Object$getPrototypeO;

        var _temp, _this, _ret;

        _classCallCheck(this, HomeComp);

        for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
        }

        return _ret = (_temp = (_this = _possibleConstructorReturn(this, (_Object$getPrototypeO = Object.getPrototypeOf(HomeComp)).call.apply(_Object$getPrototypeO, [this].concat(args))), _this), _this.state = {
            pc: _this.props.pc
        }, _temp), _possibleConstructorReturn(_this, _ret);
    }

    _createClass(HomeComp, [{
        key: 'render',
        value: function render() {
            return React.createElement(
                'div',
                null,
                'Hello ',
                this.state.pc
            );
        }
    }]);

    return HomeComp;
}(React.Component);

var ClickTest = function (_React$Component2) {
    _inherits(ClickTest, _React$Component2);

    function ClickTest() {
        _classCallCheck(this, ClickTest);

        return _possibleConstructorReturn(this, Object.getPrototypeOf(ClickTest).apply(this, arguments));
    }

    _createClass(ClickTest, [{
        key: 'ClickMe',
        value: function ClickMe() {
            alert('the button was clicked');
        }
    }, {
        key: 'render',
        value: function render() {
            return React.createElement(
                'div',
                null,
                React.createElement(
                    'div',
                    { onClick: this.ClickMe },
                    ' Click Me '
                )
            );
        }
    }]);

    return ClickTest;
}(React.Component);
Frijx
  • 11
  • 4

2 Answers2

0

class ClickTest extends React.Component {
    ClickMe(){
        alert('the button was clicked');
    };
    render() {
        return (
            <div onClick={this.ClickMe.bind(this)}>
                Click Me
          </div>
        );
    }
}

ReactDOM.render(
  <ClickTest />,
  document.getElementById('container')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

<div id="container">
    <!-- This element's contents will be replaced with your component. -->
</div>

Bind your calling method with scope 'this'

 <div onClick={this.ClickMe.bind(this)}>
            Click Me
      </div>
Jayabalaji J
  • 1,016
  • 7
  • 9
  • That has stopped the error, but when I click the div nothing happens :( – Frijx Nov 10 '17 at 09:21
  • actually it was working in fiddle..check with that – Jayabalaji J Nov 10 '17 at 09:27
  • This is React.net with MVC @Html.React is used for ReactDOM.render. The view is already rendering fine. Im getting a error though, in firebug: TypeError: ReactDOM.hydrate is not a function. Not sure if that could be causing the onClick not to register – Frijx Nov 10 '17 at 09:32
  • @Frijx "ReactDOM.hydrate is not a function" sounds like you're not loading React, or loading an older version. You need to load React for it to work client-side - ReactJS.NET just handles the server-side part, and renders a – Daniel Lo Nigro Nov 11 '17 at 22:00
  • Hi Daniel, thanks for the feed back, I am loading my react js scripts though as I can see them via the html source. All the libraries are there and are accessible, even my css is there along with my jquery libs and bootstrap js libs. Could it be the order they loaded in ? – Frijx Nov 13 '17 at 07:43
  • I think React is working and loaded though as my data binding is working fine. – Frijx Nov 13 '17 at 09:37
0

You can use fat arrow to AutoBind.

class ClickTest extends React.Component {
    ClickMe = () => {
        alert('the button was clicked');
    }
    render() {
        return (
            <div onClick={this.ClickMe}>
                Click Me
          </div>
        );
    }
}

Also the error is,

You are passing reference to your function. You should not call it. It should be this.ClickMe and not this.ClickMe()

BinaryMee
  • 2,102
  • 5
  • 27
  • 46
  • Thanks, but no alert is showing. Doesn't even register the click nothing. The view is being displayed with the div and the Click Me text but thats it. – Frijx Nov 10 '17 at 09:46
  • try using arrow function while the function is called like this:
    this.ClickMe()}> Click Me
    – Jayabalaji J Nov 10 '17 at 09:52
  • Thanks again, but That doesn't work either. The function ClickMe isnt even being created. I tried to called it from the console and its coming up as undefined. – Frijx Nov 10 '17 at 09:56
  • I guess you have issues with something else. See the working version of click here. https://jsfiddle.net/Lz3kpjoa/3/. – BinaryMee Nov 10 '17 at 10:06