Here is a small piece of code that I've tried out:
var CommentBox = React.createClass({
loadCommentsFromServer: function () {
$.ajax({
url: this.props.url,
dataType: 'json',
type: 'GET',
success: function (data) {
this.setState({data: data});
}.bind(this),
error: function (xhr, status, err) {
console.error(this.props.url, status, err.toString());
}.bind(this),
cache: false
});
},
getInitialState: function () {
return {data: []};
},
componentDidMount: function () {
this.loadCommentsFromServer();
},
render: function () {
return (
<div className="commentBox">
<MessageBox1 data={this.state.data}/>
</div>
);
}
});
var MessageBox1 = React.createClass({
getInitialState: function() {
alert('MessageBox1 getInitialState');
return {nameWithQualifier: 'Mr. ' + this.props.data.pageName};
},
componentDidMount: function() {
alert('this.props.data: ' + this.props.data);
},
render: function() {
return (<div>
<div>{this.state.nameWithQualifier}</div>
<div> {this.props.data.pageName}</div>
</div>
);
}
});
ReactDOM.render(<CommentBox url="/save/6"/>, document.getElementById('content'));
In CommentBox, I'm querying an object with ID 6 and passing it to MessageBox1 component. I want to make this object a state variable in MessageBox1 component. The problem here is, I'm not able to read the props variable. "this.props.data" is undefined in the getInitialState and ComponentDidMount of MessageBox1 component. Whereas, in the render function I can see the correct value. I've tried few examples where I'm able to read the props data in getInitialState. Why isn't this happening here? Please help. I don't have any errors in the console.