I'm building a table control which dynamically generates keys (which I understand may not be a good idea - I imagine the key should be uniquely associated with the data it represents otherwise React could just generate unique ids for us?), but either way it seems the keys are not being set and I have no idea why. The rows in the table are generated with a function that can be found here. Basically I have a helper component which takes an optional component to transform all child elements - here is one of those transform functions (from the TableBody
component):
const transformRows = (keyPrefix) => (children, passthroughProps) => (React.Children.map(children, (c, i) => {
return React.cloneElement(c, {
key: `${keyPrefix}-${i}`,
style: rowStyle,
className: rowClassName,
columnDefinitions: columnDefinitions,
rowData: tableData[i],
includeVerticalScrollbar,
...passthroughProps
});
}));
the weird thing is that when I step through the code it seems the key is being assigned, but then I get a warning in the browser Each child in an array or iterator should have a unique "key" prop
which traces back to here in the stack trace.
Any ideas?
One way to overcome this is to wrap each cloned element with React.Fragment
and set the key on the latter.
Like so:
<>
{connections.map(connection => (
<React.Fragment key={connection.id}>
{React.cloneElement(element, connection)}
</React.Fragment>
))}
</>
from the docs React.cloneElement
Unlike React.addons.cloneWithProps, key and ref from the original element will be preserved.
So if you set key for Cell, than each clone get key automaticaly.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With