Tobias Mühl Tobias Mühl - 4 months ago 8
React JSX Question

React warns about missing key on anonymous div wrapper with key'ed children

Given this code, React throws a warning that there's no unique key specified on the wrapping

div
, although it shouldn't be needed as all child components have keys specified.

class exampleComponent extends React.Component {
render() {
return (
<div>
{this.state.data.map(({uniqueId, xData}) => {
const bar = xData.map(({id}) => (
<X key={id}/>
));

const foo = <foo key={uniqueId}/>;

return (
<div> { /* No key in here, as it's not needed. Throws a warning */}
{foo}
{bar}
</div>
);

});
}
</div>
);

}
}

Answer

Instead of setting key prop for <foo /> component, you should set in to the parent <div>.

Working example:

class exampleComponent extends React.Component {
  render() {
    return (
      <div>
        {this.state.data.map(({uniqueId, xData}) => {
          const bar = xData.map(({id}) => (
            <X key={id}/>
          ));

          return (
            <div key={uniqueId}>
              <foo />
              {bar}
            </div>
          );
        });
        }
      </div>
    );
  }
}