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?

Was it helpful?

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.

OTHER TIPS

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>
          );
        })}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top