I\'m trying to return multiple React elements from a helper method. I could solve it simply by moving around some code, but I\'m wondering if there\'s a cleaner way to solve
The error message tells you exactly how to solve this:
Each child in an array or iterator should have a unique "key" prop.
Instead of this:
return [
' by ',
{this.props.author},
];
Do this:
return [
by ,
{this.props.author},
];
Yes, you need to wrap the text node ("by") in a span in order to give it a key. Such are the breaks. As you can see, I've just given each element a static key, since there's nothing dynamic about them. You could just as well use key="1" and key="2" if you wanted.
Alternatively, you could do this:
return by {this.props.author};
...which obviates the need for keys.
Here's the former solution in a working snippet:
const getAuthorUrl = author => `/${author.toLowerCase()}`;
class Foo extends React.Component {
_renderAuthor() {
if (!this.props.author) {
return null;
}
return [
by ,
{this.props.author},
];
}
render() {
return (
{this.props.datePosted}
{this._renderAuthor()}
);
}
}
ReactDOM.render( , document.getElementById('container'));