Two children with the same key in React

Nikola Lukic picture Nikola Lukic · Sep 7, 2018 · Viewed 57.9k times · Source

Application works, my classes really adds a new element but I see below warning in console!

Warning: Encountered two children with the same key, [object Object]. Keys should be unique so that components maintain their identity across updates. Non-unique keys may cause children to be duplicated and/or omitted — the behavior is unsupported and could change in a future version. in div (created by ContentBody) in ContentBody

Here is my render part :

 return (
            <div ref={this.myRef} style={this.state.myHomeStyle} >
              {this.state.elements.map((i: any) => {
                console.log(">>i>>>>", i);
                return <span style={i.myStyle} key={i} >{i}</span>;
              })}
            </div>
        );

// Where i init 
 public componentDidMount() {

    console.log('componentDidMount');
    this.myDOM  = this.myRef.current;
    this.myDOM.addEventListener(myEventsList.adaptCss, this.adaptCss);

    this.add(12,this.INLINE_TEST_ELE, null);
    this.add(13,this.INLINE_TEST_ELE, null);

  }


// Function add 
private add = (id: number, content: any, event: any ) => {

    let localArr: any[] = [];
    let mEvent: any = null;

    if (event !== undefined) {
      mEvent = event;
    }

    localArr = this.state.elements;
    localArr.push(React.createElement("div", { key: id , onClick : mEvent }, content));

    this.setState(
      {
        elements: localArr,
        visibility : true,
      },
    );

  }

Any suggestions?

Update: Here is the link for my starter project: https://github.com/zlatnaspirala/react-vs-typescript-starter

Answer

heyitsmarcucu picture heyitsmarcucu · Sep 7, 2018

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.