[31 | アイテム数の実装] << [ホーム] >> [33 | カート実装]
「qrmenu_react/src/pages/Menu.js」ファイルを編集します。
記述編集 【Desktop/QRMenu/qrmenu_react/src/pages/Menu.js】
import { Container, Row, Col, Button } from 'react-bootstrap'; import { IoCloseOutline } from 'react-icons/io5'; import { useParams } from 'react-router-dom'; import React, { useState, useEffect, useMemo } from 'react'; import { fetchPlace } from '../apis'; import styled from 'styled-components'; import MenuList from '../components/MenuList'; const OrderButton = styled(Button)` position: fixed; bottom: 20px; right: 20px; border-radius: 50%; box-shadow: 1px 1px 8px rgba(0,0,0,0.2); width: 80px; height: 80px; } `; const Menu = () => { const [ place, setPlace ] = useState({}); const [shoppingCart, setShoppingCart] = useState({}); const [showShoppingCart, setShowShoppingCart] = useState(false); const params = useParams(); const onFetchPlace = async () => { const json = await fetchPlace(params.id); console.log(json); if(json) { setPlace(json); } }; const onAddItemtoShoppingCart = (item) => { setShoppingCart({ ...shoppingCart, [item.id]:{ ...item, quantity: (shoppingCart[item.id]?.quantity || 0) + 1, } }); } const totalQuantity = useMemo( () => Object.keys(shoppingCart) .map((i) => shoppingCart[i].quantity) .reduce((a,b) => a+ b, 0), [shoppingCart] ); useEffect(() => { onFetchPlace(); }, []); return ( <Container ClassName="mt-5 mb-5"> <Row className="justify-content-center"> <Col lg={8}> <MenuList place={place} shoppingCart={shoppingCart} onOrder={onAddItemtoShoppingCart} /> </Col> </Row> {totalQuantity ? ( <OrderButton variant="standard" onClick={() => setShowShoppingCart(!showShoppingCart)}> <div Style="font-size: 13px;">注文確定</div> {showShoppingCart ? <IoCloseOutline size={25} /> : totalQuantity} </OrderButton> ) : null} </Container> ) }; export default Menu;
アイテムを注文すると、カートボタンと数量が表示されるようになりました。
↓↓クリックして頂けると励みになります。
[31 | アイテム数の実装] << [ホーム] >> [33 | カート実装]