How To Resolve "Uncaught TypeError: Failed To Construct 'Comment': Please Use The 'new' Operat....." With Respect To React JS?

- 1 answer

I have a home.jsp where within body

    <script type="text/babel" src="../resources/scripts/example.js"></script>
     <a target="_blank" rel="nofollow noreferrer" target="_blank" rel="nofollow noreferrer" href="javascript:Comment();">News</a>

In a separate example.js, I have the following

alert("I am coming here ... BEEP");

var Comment = React.createClass({
      loadCommentsFromServer: function() {
          url: this.props.url,
          dataType: 'json',
          cache: false,
          success: function(data) {
            this.setState({data: data});
          error: function(xhr, status, err) {
            console.error(this.props.url, status, err.toString());
      getInitialState: function() {
        return {data: []};
      componentDidMount: function() {
        setInterval(this.loadCommentsFromServer, this.props.pollInterval);
      render: function() {
        return (
          <div className="comment">       
            <Comment data={} />
            <span dangerouslySetInnerHTML={{__html: data}} />

      <Comment url="/workingUrl" pollInterval={2000} />,

I am getting the following error in Chrome console.

Uncaught TypeError: Failed to construct 'Comment': Please use the 'new' 
operator, this DOM object constructor cannot be called as a function.

I have added React js tags in home.jsp file.

How to fix this? Please help me.



You cannot call React Component <Comment/> by Comment(). The error requests you to create an instance of the Comment class i.e. something like this var comment = new Comment(). However, in your problem we do not need this.

  <a target="_blank" rel="nofollow noreferrer" target="_blank" rel="nofollow noreferrer" href="javascript:RenderComment();">News</a>
  <div id="content"> </div>

Your React Component <Comment/> should be independent and will be used as an argument to ReactDOM.render(...). Hence the Comment should not have ReactDOM.render(...) function inside it. Also, the anchor element click must not call Comment() as it is not a function which does rendering but rather a Class whose instance is mounted on the DOM. On clicking the <a/> tag, a RenderComment() should be called which will in turn render the <Comment/> component.

var RenderComment = function RenderComment() {
                    "div", null, " ", Comment, " "
                  ), document.getElementById("content"));

Here, we are rendering your <Comment/> component which you defined using React.createClass.

var Comment = React.createClass({
 // Your component functions and render() method
 // No ReactDOM.render() method here