Question

In a child-less React component, I'm getting the "unique key prop" error due to my use of an array inside a JSX conditional:

Each child in an array should have a unique "key" prop.

The code that's triggering the error looks like this:

<dl>
  { item.sale ? 
    [<dt>Sale</dt>,<dd className="formatted">{item.sale}</dd>,<dt>SRP</dt>,<dd>{item.srp}</dd>] :
    [<dt>Price</dt>,<dd className="formatted">{item.srp}</dd>]
  }
</dl>

I understand why the key prop is needed when rendering child components, but how do I satisfy React/JSX when the "child in an array" is an arbitrary set of child elements like this?

Était-ce utile?

La solution

React can't know that your array is static, so you get the warning. The most practical thing to do here is to write something like:

var dl;
if (item.sale) {
  dl = <dl key="sold">
    <dt>Sale</dt>
    <dd className="formatted">{item.sale}</dd>
    <dt>SRP</dt>
    <dd>{item.srp}</dd>
  </dl>;
} else {
  dl = <dl key="unsold">
    <dt>Price</dt>
    <dd className="formatted">{item.srp}</dd>
  </dl>;
}

Providing the keys on the root tells React how it should reconcile the lists when item.sale changes.

I tend to find this easier to read as well.

Autres conseils

I also had a similar issue and I solved the problem adding key={index} in the following code.

this.state.shopList.map((shop, index) => {
          return (
            <Table.Row key={index}>
              <Table.Cell collapsing>{shop.shopName}</Table.Cell>
              <Table.Cell collapsing>{shop.email}</Table.Cell>
              <Table.Cell collapsing>{shop.shopAddress}</Table.Cell>
              <Table.Cell collapsing>{shop.approved}</Table.Cell>
              <Table.Cell collapsing>{shop.iban}</Table.Cell>
            </Table.Row>
          );
        })}
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top