I'm new with React and I don't understand why this warning,
Warning: Each child in a list should have a unique "key" prop
keeps appearing when there is already a key prop on the element?
I'm using an NPM package called react-horizontal-scrolling-menu and in the package it uses JavaScript and I'm using Typescript in my React project if that makes any difference.
const list: any[] = ["items", "item2"];
const MenuItem = ({ text, selected }: {text: string, selected: string}) => {
return <div
className={`menu-item ${selected ? 'active' : ''}`}
>{text}</div>;
}
const selected: any = 'item1';
export const Menu = (list: any, selected: any) => {
list.map((el: any, index: any) => {
const { name } = el;
return <MenuItem text={name} key={name} selected={selected} />;
})
}
const Arrow = ({ text, className }: {text: string, className: any}) => {
return (
<div
className={className}
>{text}</div>
);
};
const ArrowLeft = Arrow({ text: '<', className: 'arrow-prev' });
const ArrowRight = Arrow({ text: '>', className: 'arrow-next' });
class RestaurantListIndex extends Component {
private menuItems: any;
constructor(props: any) {
super(props);
this.menuItems = Menu(list, selected);
}
state = {
selected,
// restaraunts: [
// { name: 'Ashish 11 Restaurant', type: 'North Indian, Punjabi, Chinese', rating: 4.9, deliveryTime: 45, },
// { name: 'Ashish 11 Restaurant', type: 'North Indian, Punjabi, Chinese', rating: 4.9, deliveryTime: 45, },
// { name: 'Ashish 11 Restaurant', type: 'North Indian, Punjabi, Chinese', rating: 4.9, deliveryTime: 45, },
// ],
menu: [{ imageUrl: "", name: "Testing", ingredients: "" },]
};
onSelect = (key: any) => {
this.setState({ selected: key });
}
render() {
const { selected } = this.state;
const menu = this.menuItems;
return (
<div>
<div className="pb-5 pt-3" style={{ backgroundColor: "#2D2A4B" }}>
<div className="view">
<div className="row">
<div className="col">
<h1 className="font-weight-bold text-white">Logo</h1>
</div>
<div className="col-auto">
<h6 className="text-white">icon</h6>
</div>
<div className="col-auto">
<h6 className="text-white">Login</h6>
</div>
</div>
<ScrollMenu
data={menu}
arrowLeft={ArrowLeft}
arrowRight={ArrowRight}
selected={selected}
onSelect={this.onSelect}
/>
</div>
</div>
<div className="view mt-3">
<div className="row mt-5">
<div className="col">
<h2>Menu</h2>
</div>
<div className="col-auto">
<h5>Delivery Time: <strong>45 minutes</strong></h5>
</div>
</div>
<div className="row mt-5 pt-5">
{this.state.menu.map((menuItem) => {
return <MenuItemCard
imageUrl={menuItem.imageUrl}
name={menuItem.name}
ingredients={menuItem.ingredients}
/>
})}
</div>
</div>
</div>
);
}
}
export default RestaurantListIndex;
question from:
https://stackoverflow.com/questions/65848749/why-does-this-warning-keep-appearing-when-there-is-already-a-key-prop-warning 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…