Do not use Array index in keys
10 {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">
Do not use Array index in keys
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 )
Do not use Array index in keys
20 {data
21 ? products.map((product, idx) => {
22 return (
23 <div key={idx}>24 <div
25 onClick={() =>
26 router.push(
Do not use Array index in keys
66 {filteredUsers && filteredUsers.length > 0 ? (
67 filteredUsers.map((user, idx) => {
68 return (
69 <div key={idx} className={'block'}> 70 {userID == productUserID ? (
71 <div>
72 <div
Do not use Array index in keys
148 msgs.map((m: message, idx: number) => {
149 return (
150 <div
151 key={idx}152 ref={
153 idx == msgs.length - 1
154 ? lastMsg
Do not use Array index in keys
70 {posts.map((post, idx) => {
71 return (
72 <div
73 key={idx} 74 ref={
75 idx == posts.length - 1
76 ? lastPostRef
Do not use Array index in keys
185 return (
186 <div
187 className="flex justify-center w-full"
188 key={idx}189 >
190 <img
191 src={URL.createObjectURL(
Do not use Array index in keys
16 <Product
17 product={product}
18 showDesc={false}
19 key={idx}20 />
21 )
22 })
Do not use Array index in keys
91 {images &&
92 images.map((i, idx) => (
93 <div
94 key={idx} 95 className={'flex justify-center w-full'}
96 >
97 {' '}
Description
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.
Bad Practice
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} />);
});
Recommended
cards.map((cardData) => (
<Card key={cardData.id} data={cardData} />
));
buttonData.forEach((btnData) => {
buttons.push(<Hello key={btnData.id} text={btnData.text} />);
});