Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React: Dynamically setting element keys

tl;dr -- How do I dynamically add a key to a React Element?


I have a React component that, when standing alone, has a static list of children:

<componentA>
  <child ... />
  <child ... />
  <child ... />
</componentA>

As the list is static there are no keys on any of the children as they're not needed.

Now I have another component that wraps this one and makes it's children dynamic:

function componentB(componentA) {
  return class extends React.Component {
    render() {
      const filteredChildren = // ... filter this.props.children

      return (<componentA>
        {filteredChildren}
      </componentA>)
    }
  }
}

As the children are now dynamic I need to add keys to them, but if I try something like:

React.Children.map((child, i) => {
  child.key = i;
  return child
});

it fails saying key is readonly. From this question it seems that cloneElement is a no-go as well. So is there a way to dynamically set a key?


1 Answers

Use cloneElement inside map :

React.Children.map(this.props.children, (child,  i) =>
      React.cloneElement(child, { key:  i })
 );

Known that the 2ⁿᵈ argument of React.cloneElement is the NEW props of the cloned element . One of those props is the key in this example.

like image 70
Abdennour TOUMI Avatar answered Dec 16 '25 14:12

Abdennour TOUMI



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!