I'm a beginner of ReactJS and just starting with the example code on React's official site. When I'm trying the code in section 'Fetching from the server', I can't get it to work.
I've tried both relative path
React.render(
<CommentBox url="../data/data.json" />,
document.getElementById('content')
);
and absolute path
React.render(
<CommentBox url="http://localhost/path/to/data.json" />,
document.getElementById('content')
);
But none of them has run correctly.
When I checked out the Network panel in Chrome dev tool, I saw the page didn't even send the request for data.json. Thus I got an error of Cannot read property 'comments' of undefined.
more code:
var Comment = React.createClass({
render: function() {
return (
<div className="comment">
from {this.props.author} <br/>
{this.props.children}
</div>
);
}
});
var CommentList = React.createClass({
render: function() {
var commentNodes = this.props.comments.map(function(comment){
return (
<Comment author={comment.author}>
{comment.text}
</Comment>
);
});
return (
<div className="comment-list">
{commentNodes}
</div>
);
}
});
var CommentForm = React.createClass({
render: function() {
return (
<div className="comment-form">
Hello, I am a comment form.
</div>
);
}
});
var CommentBox = React.createClass({
render: function() {
return (
<div className="comment-box">
<h1>Comments</h1>
<CommentList comments={this.props.data.comments} />
<CommentForm />
</div>
);
}
});
// ========== This won't work ===========
// React.render(
// <CommentBox url="./data/data.json" />,
// document.getElementById('content')
// );
// =========== This works. ===========
$.ajax({
type: "GET",
url: "./data/data.json",
dataType: "json",
}).done(function(res){
React.render(
<CommentBox data={res} />,
document.getElementById('content')
);
});
Any kind of help will be appreciated.
Thanks.
GETrequest in your component to retrieve theJSONdata? Here's a great example of how to retrieve data from the server.