Return multiple React elements in a method without a wrapper element Return multiple React elements in a method without a wrapper element reactjs reactjs

Return multiple React elements in a method without a wrapper element


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 ',  <a href={getAuthorUrl(this.props.author)}>{this.props.author}</a>,];

Do this:

return [  <span key="by"> by </span>,  <a key="author" href={getAuthorUrl(this.props.author)}>{this.props.author}</a>,];

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 <span> by <a href={getAuthorUrl(this.props.author)}>{this.props.author}</a></span>;

...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 [      <span key="by"> by </span>,      <a key="author" href={getAuthorUrl(this.props.author)}>{this.props.author}</a>,    ];  }  render() {    return (      <div>        {this.props.datePosted}        {this._renderAuthor()}      </div>    );  }}ReactDOM.render(<Foo datePosted="Today" author="Me"/>, document.getElementById('container'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script><script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script><div id="container"></div>