Stanley Luo Stanley Luo - 10 days ago 5
Javascript Question

Assigning key to cloned ReactJS Element

I'm trying to add props to children, using

React.cloneElement()
. But since React complains that the rendered child doesn't have a key, so I have to assign a key to them:

const extendedChildren = children.map((child, index) => {
const unkeyedElement = React.cloneElement(child, someProps);
unkeyedElement.key = index;
return tmpElement;
});


And they are rendered like this:

return (
<div>{extendedChildren}</div>
);


But then I got this error:


Uncaught TypeError: Cannot assign to read only property 'key' of
object '#'


Is there a better way of assign keys to children?

EDIT:

Object.assign({}, unkeyedElement, { key: index })
can solve the problem but I'm feeling it's an anti-pattern as I put much effort just for a key that I don't need. Any suggestion is welcomed.

Answer

if you have presets for Object spread,

const extendedChildren = children.map((child, index) => {
    return React.cloneElement(child, { ...someProps, key: index });
});

otherwise,

const extendedChildren = children.map((child, index) => {
    return React.cloneElement(child, Object.assign({}, someProps, { key: index }));
});

I put much effort just for a key that I don't need

The key in really important to React. Actually it is not passed to the component as prop but is used by React itself to aid the reconciliation of collections. This way React can handle the minimal DOM change.

Comments