Siva Sai
Siva Sai

Reputation: 396

How to resolve the unit test warning to have unique key prop

function OperatingHoursList(props: OperatingHoursProps): JSX.Element {
  const provOperatingHoursList: JSX.Element[] = [];
  if (props.operatingHours) {
    props.operatingHours.forEach(
      ({ open, close }: { open: string; close: string }) => {
        const openTime = open;
        const closeTime = close;
        if (typeof openTime === "string" && typeof closeTime === "string") {
          provOperatingHoursList.push(
            <div css={popupTimeText}>{`${timeFormatConversion(
              openTime
            )} - ${timeFormatConversion(closeTime)}`}</div>
          );
        }
      }
    );
  } else {
    provOperatingHoursList.push(<div css={popupTimeText}>Closed</div>);
  }

  return <div css={popupBottomTextTimeSection}>{provOperatingHoursList}</div>;
}

I am having a function where I am pushing the data into one array, I am facing the below error.

Facing the warning to have the key

Upvotes: -2

Views: 51

Answers (1)

Dat Huynh
Dat Huynh

Reputation: 371

A simple way is using index of element as a key

if (props.operatingHours) {
props.operatingHours.forEach(
  ({ open, close }: { open: string; close: string }, index) => {
    const openTime = open;
    const closeTime = close;
    if (typeof openTime === "string" && typeof closeTime === "string") {
      provOperatingHoursList.push(
        <div key={index} css={popupTimeText}>{`${timeFormatConversion(
          openTime
        )} - ${timeFormatConversion(closeTime)}`}</div>
      );
    }
  }
);
} else {
  provOperatingHoursList.push(<div key="closed" css={popupTimeText}>Closed</div>);
}

Upvotes: -1

Related Questions