key
prop JS-043710 let l = [];
11 imageSrcs.forEach((imageSrc, i) => {
12 l.push(
13 <img className={`flex-1 rounded w-auto h-auto ml-auto mr-auto max-w-sm md:max-w-md lg:max-w-lg xl:max-w-xl 2xl:max-w-2xl ${(index == i) ? styles.imageCarouselActiveImage : styles.imageCarouselInactiveImage}`} src={imageSrc} key={i}/>14 )
15 });
16 setImages(l);
When rendering a list of items in React, it is necessary to pass a "key" prop.
This key is used by React to identify which items have changed, are added, or are removed and should be stable.
It is not recommended to use the index of an element as key
because it doesn't uniquely identify the element.
When elements are added/removed from an array, the index of an element may change, which will result in unnecessary re-renders.
When the array is sorted, or an element is added to the beginning of the array, the indices will be changed even though the element representing an index may stay the same. This too can result in unnecessary renders.
cards.map((cardData, index) => (
<Card key={`key-is-${index}`} data={cardData}/>
));
buttonNames.map((btnText, index) => (
<Button key={index} text={btnText}/>
));
things.forEach((thing, index) => {
otherThings.push(<Hello key={index} />);
});
cards.map((cardData) => (
<Card key={cardData.id} data={cardData} />
));
buttonData.forEach((btnData) => {
buttons.push(<Hello key={btnData.id} text={btnData.text} />);
});