mardi 25 août 2015

How to correctly apply a unique key to elements in ReactJs

I have a pretty complex render statement for my ReactJs Application.

There are many nested loops to handle a lot of business logic relationships.

currently I am using a uniqueKey variable, to apply a general unique key to all components that are created through iteration:

render: function() {
    var uniqueKey = 1;

...
}

And to each element that is created in iteration I am doing something like this:

for(var k = 0; k < perspectives.length; k++){
      ...

      attributeColumns.push(
        <td key={uniqueKey++}>
          <input
            key={uniqueKey++}
            type="checkbox"
            checked={checked}
            onChange={...}>
          </input>
        </td>
      )
    }
    ...
  }

Another loop in my render function:

  for(var j = 0; j < attributes.length; j++){
    var attributeColumns = [];

    var attributeTranslationElement;
    if(attributes[j].editing) {
      attributeTranslationElement = (
        <td key={uniqueKey++}>
          <div key={uniqueKey++} style={{position:'relative'}}>
            <input
              key={uniqueKey++}
              className="form-control"
              type="text"
              style={{position:'relative'}}
              className={"translation-element-editing"}
              value={attributes[j].dimensionAttributeTranslatedName}
              onKeyDown={...}
              onChange={...} >
            </input>
            <i key={uniqueKey++}  onClick={...}></i>
            <i key={uniqueKey++} onClick={...}></i>
          </div>
        </td>);
    }
    else {
      attributeTranslationElement = (
        <td key={uniqueKey++}>
          <span key={uniqueKey++} onDoubleClick={...}>
            {attributes[j].dimensionAttributeTranslatedName}
          </span>
        </td>);
    }

I have applited the key={uniqueKey++} statement to every element in a loop, and I am still getting the warning Warning: Each child in an array or iterator should have a unique "key" prop.

Is there anything in my pattern that is causing it?

UPDATE

The problem was that I wasn't adding keys to additional elements that I was adding outside of the loop.

e.g.

tableHeaders.unshift(<th key={uniqueKey++} className="col-xs-1">   {"Translation"} </th>);
tableHeaders.unshift(<th key={uniqueKey++} className="col-xs-1">{...}</th>);
tableHeaders.unshift(<th key={uniqueKey++} className="col-xs-1">{"object type"} </th>);

Once I added the key prop to these, the error went away.




Aucun commentaire:

Enregistrer un commentaire