Untitled

mail@pastecode.io avatar
unknown
javascript
a year ago
1.7 kB
1
Indexable
Never
import React, { useState } from 'react';
import { ListGroup, ListGroupItem, Button } from 'reactstrap';

const Basket = () => {
  const [items, setItems] = useState([
    { id: 1, name: 'Item 1', price: 10.99 },
    { id: 2, name: 'Item 2', price: 15.99 },
    { id: 3, name: 'Item 3', price: 5.99 },
  ]);

  const [selectedItems, setSelectedItems] = useState([]);

  const addItemToBasket = (item) => {
    setSelectedItems([...selectedItems, item]);
  };

  const removeItemFromBasket = (itemId) => {
    setSelectedItems(selectedItems.filter(item => item.id !== itemId));
  };

  const calculateTotal = () => {
    return selectedItems.reduce((total, item) => total + item.price, 0);
  };

  return (
    <div>
      <h2>Your Basket</h2>
      <ListGroup>
        {selectedItems.map(item => (
          <ListGroupItem key={item.id}>
            <div className="d-flex justify-content-between align-items-center">
              <span>{item.name} - ${item.price}</span>
              <Button color="danger" onClick={() => removeItemFromBasket(item.id)}>Remove</Button>
            </div>
          </ListGroupItem>
        ))}
      </ListGroup>

      <h3>Total: ${calculateTotal().toFixed(2)}</h3>

      <h2>Available Items</h2>
      <ListGroup>
        {items.map(item => (
          <ListGroupItem key={item.id}>
            <div className="d-flex justify-content-between align-items-center">
              <span>{item.name} - ${item.price}</span>
              <Button color="success" onClick={() => addItemToBasket(item)}>Add</Button>
            </div>
          </ListGroupItem>
        ))}
      </ListGroup>
    </div>
  );
};

export default Basket;