Skip to content

Instantly share code, notes, and snippets.

@codecademydev

codecademydev/GroceryCart.js Secret

Created Nov 5, 2020
Embed
What would you like to do?
Codecademy export
import React, { useState } from "react";
import ItemList from "./ItemList";
import { produce, pantryItems } from "./storeItems";
export default function GroceryCart() {
const [cart, setCart] = useState([]);
const addItem = (item) => {
setCart((prev) => {
return [item, ...prev];
});
};
const removeItem = (targetIndex) => {
setCart((prev) => {
return prev.filter((item, index) => index !== targetIndex);
});
};
return (
<div>
<h1>Grocery Cart</h1>
<ul>
{cart.map((item, index) => (
<li onClick={() => removeItem(index)} key={index}>
{item}
</li>
))}
</ul>
<h2>Produce</h2>
<ItemList items={produce} onItemClick={addItem} />
<h2>Pantry Items</h2>
<ItemList items={pantryItems} onItemClick={addItem} />
</div>
);
}
import React from "react";
export default function ItemList({ items, onItemClick }) {
const handleClick = ({ target }) => {
const item = target.value;
onItemClick(item);
};
return (
<div>
{items.map((item, index) => (
<button value={item} onClick={handleClick} key={index}>
{item}
</button>
))}
</div>
);
}
export const produce = [
"Carrots",
"Cucumbers",
"Bell peppers",
"Avocados",
"Spinach",
"Kale",
"Tomatoes",
"Bananas",
"Lemons",
"Ginger",
"Onions",
"Potatoes",
"Sweet potatoes",
"Purple cabbage",
"Broccoli",
"Mushrooms",
"Cilantro"
];
export const pantryItems = [
"Chia",
"Goji berries",
"Peanut butter",
"Bread",
"Cashews",
"Pumpkin seeds",
"Peanuts",
"Olive oil",
"Sesame oil",
"Tamari",
"Pinto beans",
"Black beans",
"Coffee",
"Rice",
"Dates",
"Quinoa"
];
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment