PROGRAMING/React

[REACT] Simple shopping cart

donghunl 2024. 3. 7. 06:30
반응형

Build a shopping cart that displays the total price when adding items.

 

Implement the Add to Cart logic, add an item to the cart when the button is clicked.

Implement the + and - buttons to add or remove items from the cart.

Implement the total sum at the bottom of the page.

 

ShoppingCart.js

import { useState } from 'react'

const items = [{
  name: 'apple',
  price: 0.79
}, {
  name: 'banana',
  price: 0.39
}, {
  name: 'cherry tomatoes',
  price: 3.99
}]

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

  const addToCart = (item) => {
    const cartCopy = [...cart]
    const itemInCart = cartCopy.find(i => item.name === i.name)
    if (itemInCart) {
      itemInCart.quantity += 1
      setCart(cartCopy)
    } else {
      setCart(prevCart => [...prevCart, { ...item, quantity: 1 }])
    }
  }

  const increase = (name) => {
    const cartCopy = [...cart]
    const item = cartCopy.find(i => i.name === name)
    item.quantity += 1
    setCart(cartCopy)
  }

  const decrease = (name) => {
    let cartCopy = [...cart]
    const item = cartCopy.find(i => i.name === name)
    if (item.quantity > 1) {
      item.quantity -= 1
    } else {
      cartCopy = cartCopy.filter(i => i.name !== name)
    }
    setCart(cartCopy)
  }

  return (
    <div>
      <h1>Shopping Cart</h1>
      <div className='cart'>
        <div className='items'>
          <h2>Items</h2>
          {items.map(item => (
            <div key={item.name}>
              <h3>{item.name}</h3>
              <p>${item.price}</p>
              <button onClick={() => addToCart(item)}>Add to Cart</button>
            </div>)
          )}
        </div>
        <div>
          <h2>Cart</h2>
          {cart.length > 0
            ? cart.map(item => (
              <div key={item.name}>
                <h3>{item.name}</h3>
                <p>
                  <button onClick={() => decrease(item.name)}>-</button>
                  {item.quantity}
                  <button onClick={() => increase(item.name)}>+</button>
                </p>
                <p>Subtotal: ${(item.quantity * item.price).toFixed(2)}</p>
              </div>
              ))
            : <p>Add an item to your cart</p>}
        </div>
      </div>
      <div className='total'>
        <h2>Total: ${cart.reduce((acc, i) => acc + (i.quantity * i.price), 0).toFixed(2)}</h2>
      </div>
    </div>
  )
}

export default ShoppingCart

 

App.js

import ShoppingCart from './ShoppingCart'
function App () {
  return (
    <div className='App'>
      <ShoppingCart />
    </div>
  )
}

export default App

 

index.css

html, body {
  font-family: sans-serif;
}

.page {
  height: 100vh;
  width: 100vw;
  display: flex;
  align-items: center;
  justify-content: center;
}

button {
  padding: 10px;
  margin: 5px;
  outline: none;
  border: 2px solid white;
}

body {
  padding: 0px;
  margin: 0px;
}

input, label {
  display: block;
  margin: 8px auto;
}

input {
  padding: 8px;
  width: 300px;
}

input[type=submit] {
  width: 100px;
}

h1 {
  text-align: center;
}

.items {
  padding-left: 15px;
}

.cart {
  display: flex;
  flex-direction: row;
  justify-content: space-around;
}

.total {
  margin: 0 auto;
  text-align: center;
}

button {
  margin:0 5px;
}

 

결과 화면

반응형

'PROGRAMING > React' 카테고리의 다른 글

[React] Ternary operators  (65) 2024.04.25
[React] 화살표 함수 (Arrow Functions)  (111) 2024.04.18
[REACT] Focus an input - useRef  (1) 2024.03.07
[REACT] Simple calculator - useReducer  (1) 2024.03.07
[REACT] Pixel art - React Context  (0) 2024.03.07