Wasteland Wasteland - 2 months ago 20
React JSX Question

Reactjs - array/iterator key

I've got the following error:


warning.js?0260:45Warning: Each child in an array or iterator should
have a unique "key" prop. Check the render method of
Tabs
.


render() {

const { tabs } = this.props;
const { active } = this.state;
return (
<div>
<ButtonToolbar>
{tabs.map(listValue =>
<Button onClick={() => this.handleClick(listValue)}>
{listValue}
</Button>
)}
</ButtonToolbar>

// Display the chosen tab
{this.showTab(active)}



</div>
);


Where would I add the id property in this case. I've tried:

<ButtonToolbar>
{tabs.map(listValue =>
<Button key={listValue.id} onClick={() => this.handleClick(listValue)}>
{listValue}
</Button>
)}
</ButtonToolbar>


But it does not get rid of the error. Please advise

Answer

You can use map's iterator for this:

<ButtonToolbar>
  {tabs.map((listValue, key) =>
    <Button              ^--- here
      key={key}   <--- and here.
      onClick={() => this.handleClick(listValue)}
    >
      {listValue}
    </Button>)
  }
</ButtonToolbar>

Reference

Comments