Reputation: 336
I am following a React JS example from CodeSchool. I have been able to follow the examples. The problem is when I try to implement an IF conditional to pass different data to a Component. The component not shown is the 'Comment'. Look inside the _getComments
function. If I use an If conditional, see fiddle: https://jsfiddle.net/joelgb/vxtkpzog/15/, to decide which array will be passed, the code will not work. But if I simply put the below code without any If
the Component Comment is rendered correctly.
const commentsList = [
{id: 1, author: "author1", body: "body1"},
{id: 2, author: "author2", body: "body2"},
{id: 3, author: "author3", body: "body3"}
];
Note that using this approach, it won't work.
var commentsList;
if (a=='a'){
commentsList = [
{id: 1, author: "author1", body: "body1"},
{id: 2, author: "author2", body: "body2"},
{id: 3, author: "author3", body: "body3"}
];
}
else
{
commentsList = [
{id: 1, author: "author4", body: "body4"},
{id: 2, author: "author5", body: "body5"},
{id: 3, author: "author6", body: "body6"}
];
}
Can anyone point me towards the error?
Upvotes: 0
Views: 38
Reputation: 28397
You almost got it right, you forgot to call comments()
This
class CommentBox extends React.Component{
render() {
const comments = this._getComments.bind(this,'a');
return (
<div>
<h3>Comments</h3>
{comments} // <--- You are not calling comments
<button onClick={this._getComments.bind(this,'b')}>north</button>
</div>
);
}
...
}
should be
class CommentBox extends React.Component{
render() {
const comments = this._getComments.bind(this,'a');
return (
<div>
<h3>Comments</h3>
{comments()}
<button onClick={this._getComments.bind(this,'b')}>north</button>
</div>
);
}
...
}
Upvotes: 1