My Blog

My WordPress Blog

My Blog

My WordPress Blog

Simple Shopping Cart

This example demonstrates how to build a basic shopping cart with the ability to add and remove items.

jsxCopy codeimport React, { useState } from 'react';
import ReactDOM from 'react-dom';

const items = [
  { id: 1, name: 'Apple', price: 1 },
  { id: 2, name: 'Banana', price: 0.5 },
  { id: 3, name: 'Orange', price: 0.8 },
];

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

  const addItem = (item) => {
setCart([...cart, item]);
}; const removeItem = (id) => {
setCart(cart.filter(item => item.id !== id));
}; const total = cart.reduce((acc, item) => acc + item.price, 0); return (
<div>
  <h1>Shopping Cart</h1>
  <h2>Items:</h2>
  <ul>
    {items.map(item => (
      <li key={item.id}>
        {item.name} - ${item.price}
        <button onClick={() => addItem(item)}>Add to Cart</button>
      </li>
    ))}
  </ul>
  <h2>Cart:</h2>
  <ul>
    {cart.map(item => (
      <li key={item.id}>
        {item.name} - ${item.price}
        <button onClick={() => removeItem(item.id)}>Remove</button>
      </li>
    ))}
  </ul>
  <h3>Total: ${total.toFixed(2)}</h3>
</div>
); } ReactDOM.render(<ShoppingCart />, document.getElementById('root'));
Simple Shopping Cart

Leave a Reply

Your email address will not be published. Required fields are marked *

Scroll to top