React JSX: a unique key in a conditional array

In the React child component, I get the error "unique key prop" due to my use of the array inside the JSX condition:

Each child in the array must have a unique "key" support.

The code causing the error is as follows:

<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 key support is required when rendering child components, but how can I satisfy React / JSX when the "child in the array" is an arbitrary set of children like this?

+4
source share
1 answer

React , , . - - :

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>;
}

, item.sale.

, .

+8

Source: https://habr.com/ru/post/1527577/


All Articles