key
prop JS-043710 {data &&
11 products.map((obj, idx) => {
12 return (
13 <div className="mb-10" key={idx}>14 {obj.images ? (
15 <>
16 <div className="card w-72 card-bordered card-compact lg:card-normal border-solid border-black bg-white">
12 <h1 className="font-bold text-xl">Latest Products</h1>
13 {data.map((p, idx) => {
14 return (
15 <div key={idx}>16 <ProductCard product={p} showDesc={true} />
17 </div>
18 );
20 {data
21 ? products.map((product, idx) => {
22 return (
23 <div key={idx}>24 <div
25 onClick={() =>
26 router.push(`products/${product.name}`)
81 ref={idx == posts.length - 1 ? lastPostRef : null}
82 >
83 <Post
84 key={idx} 85 showProductIcon={true}
86 data={p}
87 channel={channel}
77 posts.map((p, idx) => {
78 return (
79 <div
80 key={idx} 81 ref={idx == posts.length - 1 ? lastPostRef : null}
82 >
83 <Post
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} />);
});