Reputation: 932
React v15.1
I am creating a table with a variable number of rows, depending on the data provided via props
. Here is where I am (and it works fine):
getRows = () => {
const rows = [];
for (const col in this.props.tableRows) {
if ({}.hasOwnProperty.call(this.props.tableRows, col)) {
rows.push(React.cloneElement(this.props.tableRows[col], {}));
}
}
return rows;
}
I am working on making the console warnings disappear. This old favorite is appearing Each child in an array or iterator should have a unique "key" prop. Check the render method of 'TableData'.
What is the best way to add a key to cloned elements that I am pushing to an empty array?
OR is there a better way to handle this data on dynamically-generated table rows?
This is for an upload dialog for contact information I am using in many places. It successfully performs as expected, just need to add a key...or make it even better.
Upvotes: 2
Views: 13706
Reputation: 13138
@medet-tleukabiluly has the right answer:
keyed_items = items.map((item, key) => React.cloneElement(item, {key}))
as long as each item is an element (not just a string).
Upvotes: 2
Reputation: 12966
It would probably make more sense to use the .map
function and render JSX so you can easily assign a key to each table row.
function getRows() {
const {tableRows} = this.props;
return tableRows.map((row, index) =>
<tr key={index}>
// whatever else you wanted to add inside each row
</tr>
);
}
This is mostly just a guess for what you're trying to do - if it doesn't work for you, please post a comment that describes your problem in more detail and I can edit this answer to provide a better solution for you.
Upvotes: 0