Zeke Dran Zeke Dran - 3 months ago 17
React JSX Question

React using JS var inside quotes

I just started learning React using tutorials on React site

I wanted to use ids for each element inside JSON array. After referring to this link, I tried

<div className="commentListElement" key={key} id={"comment-"+{key}} >
it in my code, but it didn't work.


It shows
comment-[object Object]



And sadly
${key}
is also not working...!

Here's my code:

var data = [
{id: 1, author: "Pete Hunt", text: "Sample Comment 1"},
{id: 2, author: "Virginia Woolf", text: "Sample Comment 2"}
]

var CommentList = React.createClass({
render: function() {
var commentNodes = this.props.data.map(function(comment, key) {
return (
<div className="commentListElement" key={key} id={"comment-"+{key}} >
Key: {key} <br />
ID: {comment.id} <br />
Commented by {comment.author} <br />
Comment: {comment.text}
</div>
);
});
return (
<div className="commentList">
{commentNodes}
</div>
);
}
})

var CommentBox = React.createClass({
render: function() {
return (
<div className="commentBox">
Hello, world! I am a CommentBox.
<CommentList data={data} />
</div>
);
}
});
ReactDOM.render(
<CommentBox />,
document.getElementById('content')
);


But I see this in my browser

enter image description here

What am I doing wrong?

Answer

In JSX inside curly braces you should write javascript expression, so that this should work:

id={"comment-"+key}

Furthermore it is not a good practice to use array indexes as keys of react elements. You should use some kind of business identifier e.g. comment.id.