Two children with the same key in React

See this for more understanding in "key" related warnings and best practices

 function ListItem(props) {
  // Correct! There is no need to specify the key here:
  return <li>{props.value}</li>;
}

function NumberList(props) {
  const numbers = props.numbers;
  const listItems = numbers.map((number) =>
    // Correct! Key should be specified inside the array.
    <ListItem key={number.toString()}
              value={number} />

  );
  return (
    <ul>
      {listItems}
    </ul>
  );
}

const numbers = [1, 2, 3, 4, 5];
ReactDOM.render(
  <NumberList numbers={numbers} />,
  document.getElementById('root')
);

Visit this link https://reactjs.org/docs/lists-and-keys.html#extracting-components-with-keys for more information


You can pass another parameter within your map function like so:

this.state.elements.map((element, index) => {
   return <span style={element.myStyle} key={index} >{element}</span>;
});

The second parameter of the Array.prototype.map function actually contains the current index of the particular element in that array.

This way, you'll be sure that your key is not duplicated.


You are passing element not index. And if your element is same then the error is being thrown. To pass the index use second param:

.map((element, index)=>

Now, using index will give you different key.

Tags:

Key

Add

Reactjs