CartItem.js 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. import { Box } from "@mui/system";
  2. import defaultGoodImage from "../../images/default-good-image.png";
  3. import { IoCloseOutline } from "react-icons/io5";
  4. import { AiOutlinePlus, AiOutlineMinus } from "react-icons/ai";
  5. import { actionCartChange } from "../../reducers";
  6. import { useEffect, useState } from "react";
  7. import { backendURL, mediaURL } from "../../helpers";
  8. import { Typography, Stack, IconButton, TableCell, TableRow } from "@mui/material";
  9. import { connect } from "react-redux";
  10. export const CartItem = ({ order, onDeleteClick, onChange }) => {
  11. const { good, count = 1 } = order || {};
  12. const { _id, images = [], name = "", price = 0, amount = 1 } = good;
  13. const [countInput, setCountInput] = useState(count || 1);
  14. useEffect(() => {
  15. setCountInput(+count);
  16. }, [count]);
  17. useEffect(() => {
  18. onChange(good, +countInput);
  19. }, [countInput]);
  20. const handleChange = (count) => {
  21. if (count >= 0 && count <= 99 && count <= amount) {
  22. setCountInput(+count);
  23. }
  24. };
  25. return (
  26. <TableRow className="CartItem">
  27. <TableCell>
  28. <Box
  29. component="img"
  30. src={images && images[0]?.url ? `${backendURL}${mediaURL}${images ? images[0]?.url : ""}` : defaultGoodImage}
  31. sx={{ width: 50 }}
  32. onError={({ currentTarget }) => {
  33. currentTarget.onerror = null;
  34. currentTarget.src = defaultGoodImage;
  35. }}
  36. />
  37. </TableCell>
  38. <TableCell>
  39. <Box sx={{ flexGrow: 1 }}>
  40. <Typography variant="h5">{name}</Typography>
  41. <Typography variant="body1">{price} ₴</Typography>
  42. </Box>
  43. </TableCell>
  44. <TableCell>
  45. <Stack justifyContent="center" direction="row" alignItems="center">
  46. <IconButton onClick={() => handleChange(countInput - 1)}>
  47. <AiOutlineMinus />
  48. </IconButton>
  49. <Typography>{countInput}</Typography>
  50. <IconButton onClick={() => handleChange(countInput + 1)}>
  51. <AiOutlinePlus />
  52. </IconButton>
  53. </Stack>
  54. </TableCell>
  55. <TableCell>
  56. <Stack justifyContent="center">
  57. <Typography variant="body1" textAlign="center">
  58. {price * count} ₴
  59. </Typography>
  60. </Stack>
  61. </TableCell>
  62. <TableCell>
  63. <IconButton onClick={() => onDeleteClick({ _id, images, name, price })}>
  64. <IoCloseOutline />
  65. </IconButton>
  66. </TableCell>
  67. </TableRow>
  68. );
  69. };
  70. export const CCartItem = connect(null, { onChange: (good, countInput) => actionCartChange(good, +countInput) })(CartItem);