React

by oktaviardi pratama

HTML

<div id="root"></div>

CSS

body {
  font-family: sans-serif;
  padding: 20px;
  background-color: #f4f4f9;
}

.app-container {
  display: flex;
  gap: 40px;
}

.products, .cart {
  border: 1px solid #ccc;
  padding: 20px;
  border-radius: 8px;
  background: white;
  min-width: 250px;
}

.product-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

button {
  cursor: pointer;
  padding: 5px 10px;
  background-color: #007bff;
  color: white;
  border: none;
  border-radius: 4px;
}

button:hover {
  background-color: #0056b3;
}

React

// Destructure Hooks from the global React object since we are in a browser/fiddle env
const { useState } = React;

// Sample Data
const PRODUCTS = [
  { id: 1, name: 'Apple', price: 0.99 },
  { id: 2, name: 'Banana', price: 0.49 },
  { id: 3, name: 'Orange', price: 0.79 },
];

function App() {
  const [cart, setCart] = useState([]);

  // Function to add item to cart
  const addToCart = (product) => {
    setCart((prevCart) => {
      // Check if the item already exists in the cart
      const existingItem = prevCart.find((item) => item.id === product.id);

      if (existingItem) {
        // If it exists, map through and increase the quantity
        return prevCart.map((item) =>
          item.id === product.id ? { ...item, quantity: item.quantity + 1 } : item
        );
      }

      // If it's a new item, add it with a quantity of 1
      return [...prevCart, { ...product, quantity: 1 }];
    });
  };

  // Calculate total price
  const totalPrice = cart.reduce((sum, item) => sum + item.price * item.quantity, 0);

  return (
    <div className="app-container">
      {/* Product List */}
      <div className="products">
        <h2>Products</h2>
        {PRODUCTS.map((product) => (
          <div key={product.id} className="product-item">
            <span>{product.name} - ${product.price.toFixed(2)}</span>
            <button onClick={() => addToCart(product)}>Add to Cart</button>
          </div>
        ))}
      </div>

      {/* Shopping Cart */}
      <div className="cart">
        <h2>Your Cart</h2>
        {cart.length === 0 ? (
          <p>Your cart is empty.</p>
        ) : (
          <div>
            <ul>
              {cart.map((item) => (
                <li key={item.id}>
                  {item.name} x {item.quantity} (${(item.price * item.quantity).toFixed(2)})
                </li>
              ))}
            </ul>
            <hr />
            <h3>Total:...