React - Total based on its key - SOS

React - Total based on its key - SOS
0

#1

GITHUB REPOSITORY PROJECT

GIFo

This is updating all the products => <div>Bottles: {product.winePrice * this.state.quantity}</div>
Right now they are all the same for obvious reasons…

I think it might confusing but bottles is the total based on the quantity of the individual product

The object I am passing as props

  products: [
            { wineName: 'Red', winePrice: 30, quantity_bottle: 4, id: 1 },
            { wineName: 'White', winePrice: 30, quantity_bottle: 5, id: 2 },
            { wineName: 'Pink', winePrice: 30, quantity_bottle: 6, id: 3 },
        ]

They show the same value because they all have the same price and then all of them are multiplied for this.state.quantity which contains the value of the input of the last one of the three that has been incremented.

import React, { Component } from 'react'

class Products extends Component {
    state = {
        quantity: 1
    }

    handleChange(event) {
        this.setState({ quantity: event.target.value })
    }

    render() {
        const { products } = this.props;
        const productsList = products.map(product => {
            return (
                <div className="wineBox" key={product.id}> <= Here its key
                    <div>Name: {product.wineName}</div>
                    <div>Price: {product.winePrice}</div>
                    <div>Subtotal: {product.quantity_bottle}</div>
          Here =>   <div>Bottles: {product.winePrice * this.state.quantity}</div>
                    <div>Quantity: <input type="number" defaultValue={1} max={product.quantity_bottle} min={1} onChange={this.handleChange.bind(this)} / ></div>
                </div>


            )
        });

        return (
            <div className="container-fluid">
                {productsList}
            </div>
        )

    }
}


export default Products

#2

I don tell whole solution, but you can set the id to input and compare with ternary operator with product.id and if is equal make an product.id===i ? {product.winePrice * this.state.quantity}: 1
from
products.map((product,i) => {


#3

I solved it before reading your edited comment.

I don tell whole solution, but you can set the id to input and compare with ternary operator

It was enough for me to understand, I couldn’t figure out a way to get the key.

 handleChange(event) {
        this.setState({ quantity: event.target.value, key: event.target.id })
    }
 {this.state.key == product.id ? product.winePrice * this.state.quantity : product.winePrice}

Thank you so much.


#4

I was thinking about something like that and I am happy you show me that.