0

I'm new to react and I tried adding items to a list.

According to the react documentation, given in the error message, there should only be a key on the ListItem.

It doesn't work either with putting a key on every child element. Also, according to react it's the incorrect way.

class List extends React.Component {

  listItemNumbers;
  listItems;

  constructor(props) {
      super(props);
      this.listItemNumbers = ["1","2","3","4","5"];
      this.listItems = this.listItemNumbers.map((i) => <ListItem key={"item_" + i} value={i} name={"test"} text={"test"}/>)
  }

  render() {
      return <ul className="mdc-list">
          {this.listItems}
      </ul>
    }
}

// export default List;

class ListItem extends React.Component {

  name;
  text;

  constructor(props) {
      super(props);
  }

  render() {
      return <li className="mdc-list-item"><span className="mdc-list-otem__text">{this.props.name}</span></li>;
    }

  componentDidMount() {
  }
}

ReactDOM.render(<List />, document.getElementById("root"));
<div id="root"></div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.development.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.development.js"></script>

Warning :

Each child in a list should have a unique "key" prop.

yannh
  • 392
  • 5
  • 14
  • 1
    Possible duplicate of [Understanding unique keys for array children in React.js](https://stackoverflow.com/questions/28329382/understanding-unique-keys-for-array-children-in-react-js) – Chris Ngo Jul 09 '19 at 08:00
  • 1
    I've moved your code into a Stack Snippet. As you can see, the error (warning) does not occur in the code in the question. I suspect you probably have some *other* component somewhere that's triggering the error. For next time, [here's how to do a Stack Snippet with React (including JSX)](http://meta.stackoverflow.com/questions/338537/). – T.J. Crowder Jul 09 '19 at 08:03

1 Answers1

0

I solved the problem. It happened because I used a list in App.js to display the components.

yannh
  • 392
  • 5
  • 14