Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React cloneElement not setting key

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?

like image 516
Jordan Avatar asked May 20 '16 19:05

Jordan


2 Answers

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>
    ))}
  </>

like image 151
Izhaki Avatar answered Oct 18 '22 00:10

Izhaki


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.

like image 24
VelikiiNehochuha Avatar answered Oct 17 '22 23:10

VelikiiNehochuha