I have one parent component that renders the total sum of the subtotals that are within children components.
function Total({ products }) {
const [total, setTotal] = useState(0);
const handleChildToParent = (subtotal) => {
setTotal(total + subtotal);
};
return (
<div>
{products.map((product) => (
<Subtotal product={product} childToParent={handleChildToParent} />
))}
<span>Total: {total}</span>
</div>
);
}
Each Subtotal component takes in the price of an item, and calculates the subtotal based on how many units the user chooses.
function Subtotal({ product, childToParent }) {
const [units, setUnits] = useState(0);
const handleInputChange = (value) => {
setUnits(value);
childToParent(value * product.price);
};
return (
<div>
<input
type="number"
min={1}
onChange={(e) => handleInputChange(e.target.value)}
value={units}
/>
<span>units * product price: {units * product.price}</span>
</div>
);
}
My goal is to have a dynamic total in the parent component based on the information of its children. For example: the user chooses two items with price of $100 each, and three with price $12, the parent component should display $236, and the child components should display $200 ($100x2) for the first item, and $36 ($12x3) for the second item (this is what I currently have), and that if the user changes his mind on the first item and instead of two wants to get just one, the total price should update to $136. When I try to subtract an item I'm stuck. I've tried setting an initial sum of items and using useEffect with total but I can't get to the solution. Any help will be appreciate it, I actually don't know if this is really possible using child to parent communication between components.
Here's a sandbox of what I have: https://codesandbox.io/s/reverent-elbakyan-i0hr1