user911625
user911625

Reputation:

In React how to add key prop to element passed as Object

Approximately the code looks like this (CoffeeScript)

//In Parent component

render: () ->

  mycomp = <SomeComponent some_prop="something" />

  <ChildComponent passedComp = mycomp />


//In Child component

render: () ->

 someContent = [passedComp, <AnotherComp key={2} />]


 <div>
   {someContent}
 </div>

This generates a warning about missing key in the array in Child component.

The problem is how to add key={1} to passedComp in Child component. I can't do it in the render method of the Parent (alongside some_prop) because I can't know at this point what key should be. I need to add the key prop in the Child component - but here passedComp is already an object .

How can I modify passedComp to have a key?

I have

someContent = [<span key={1}>{passedComp}</span>, <AnotherComp key={2} />]

which gets rid of the React warning but the extra span breaks my (well react-bootstrap's) CSS. Is there a better solution?

Upvotes: 9

Views: 19837

Answers (3)

qwertzguy
qwertzguy

Reputation: 17687

You can use a React.Fragment to add a key without breaking CSS and without the need to clone:

someContent = [<React.Fragment key={1}>{passedComp}</React.Fragment>, <AnotherComp key={2} />]

Upvotes: 24

Damien Leroux
Damien Leroux

Reputation: 11693

The only way to do it if your component is already instantiated is to clone your component and add the key property

Upvotes: 7

brenmcnamara
brenmcnamara

Reputation: 469

For anyone else who stumbled across this:

Another potential way of injecting a Key is to add a dummy parent as follows:

With ES6 syntax:

class KeyedComponent extends Component {
  render() {
    // NOTE: This implementation assumes that your dummy component has
    // a single child.
    const child = React.Children.only(this.props.children);
    return child;
  }
}

// Use as follows:

// Stuff before...

render() {
  const someContent = [
    <KeyedComponent key="1">{passedComp}</KeyedComponent>,
    <AnotherComp key="2" />,
  ];
  // Stuff after...
}

Upvotes: 4

Related Questions