After running "yarn run dev", I am met with the following error:
Warning: Each child in a list should have a unique "key" prop. Check the top-level render call using . See https://reactjs.org/link/warning-keys for more information. at StarIcon at Product (webpack-internal:///./src/components/Product.js:24:20) at Div at ProductFeed (webpack-internal:///./src/components/ProductFeed.js:13:24) at main at div at Home (webpack-internal:///./src/pages/index.js:18:17)
Here is my Product.js file:
import React from 'react'
import Image from "next/image";
import { useState } from "react";
import { StarIcon } from "@heroicons/react/solid";
import * as CurrencyFormat from 'react-currency-format';
// import Currency from "react-currency-formatter";
const MAX_RATING = 5;
const MIN_RATING = 1;
function Product({id, title, price, description, category, image}) {
const [rating] = useState(
Math.floor(Math.random() * (MAX_RATING - MIN_RATING 1)) MIN_RATING
);
const [hasPrime] = useState(Math.random() < 0.5)
return (
<div className='relative flex flex-col m-5 bg-white z-30 p-10'>
<p className='absolute top-2 right-2 text-xs italic text-gray-400'>{category}</p>
<Image src={image} height={200} width={200} style="contain"></Image>
<h4 className='my-3'>{title}</h4>
<div className='flex'>
{Array (rating)
.fill()
.map((_, i) => (
<StarIcon className='h-5 text-yellow-500'></StarIcon>
))}
</div>
<p className='text-xs my-2 line-clamp-2'>{description}</p>
<div className='mb-5'>
<CurrencyFormat value={price} prefix={'$'}></CurrencyFormat>
</div>
{hasPrime && (
<div className='flex items-center spaxe-x-2 -mt-5'>
<img className='w-12' src='https://links.papareact.com/fdw' alt=""></img>
<p className='text-xs text-gray-500'>FREE Next-Day Delivery</p>
</div>
)}
<button className='mt-auto button'>Add to Basket</button>
</div>
)
}
export default Product
I have attempted to use several different types of key props throughout the files and none of the formats seem to resolve this issue. Surely I am going about this wrong. Any help here would be greatly appretiated!!
CodePudding user response:
Try passing a unique key while iterating i.e .map your code should look something like this
<div className='flex'>
{Array (rating)
.fill()
.map((_, i) => (
<StarIcon className='h-5 text-yellow-500' key={i}>
</StarIcon>
))}
</div>
CodePudding user response:
This warning is addressed in the React docs.
When you run this code, you’ll be given a warning that a key should be provided for list items. A “key” is a special string attribute you need to include when creating lists of elements.
...
Keys help React identify which items have changed, are added, or are removed. Keys should be given to the elements inside the array to give the elements a stable identity.
Example code from the docs:
const numbers = [1, 2, 3, 4, 5];
const listItems = numbers.map((number) =>
<li key={number.toString()}>
{number}
</li>
);