How to resolve "Uncaught TypeError: Failed to construct 'Comment': Please use the 'new' operat....." with respect to React JS?
Maybe this will help someone who had the same issue as me...I simply forgot to import the component I was trying to render (using ES6):
import { Comment } from './comment'
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.
<body>
<a href="javascript:RenderComment();">News</a>
<div id="content"> </div>
</body>
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() {
ReactDOM.render(React.createElement(
"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
}