File size: 2,297 Bytes
f5071ca
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
import React from 'react'
import './Product.css'
import StarIcon from '@material-ui/icons/Star';
import { toast } from 'react-toastify';
import StarHalfIcon from '@material-ui/icons/StarHalf';
import StarOutlineIcon from '@material-ui/icons/StarBorder';
import { useStateValue } from '../../context/StateProvider';

function Product({ id, title, price, rating, image }) {

    const [{ cart }, dispatch] = useStateValue()
    let halfRating = (rating - Math.floor(rating)) * 10;
    let outline = 0;

    halfRating > 0 ? outline = (5 - Math.ceil(rating)) : outline = (5 - Math.floor(rating))

    const addToCart = () => {
        // Add item to basket
        dispatch({
            type: 'ADD_TO_CART',
            payload: { id, title, price, rating, image }
        })
        toast.info(`${title} added worth \n ₹${price}`);
    }

    return (
        <div className="product">
            <img src={image} alt={title} />
            <div className="product__info">
                <p>{title}</p>
                <div className="product__group">
                    <p className="product__price">
                        <small>₹.</small>
                        <strong>{price}</strong>
                    </p>
                    <div className="product__rating">
                        {
                            Array(Math.floor(rating))
                                .fill()
                                .map((_, index) => (
                                    <StarIcon key={index} />
                                ))
                        }
                        {
                            (halfRating > 0) ? <StarHalfIcon /> : <></>
                        }
                        {
                            outline > 0 ? (
                                Array(outline)
                                    .fill()
                                    .map((_, index) => (
                                        <StarOutlineIcon key={index} />
                                    ))
                            )
                                : ""
                        }
                    </div>
                </div>
            </div>

            <button onClick={addToCart}>Add to Cart</button>
        </div>
    )
}

export default Product