My example is a simple order form.
I have a main component (Order) and inside this component I render dynamic list of child components (OrderLine)
class Order extends React.Component {
...
render() {
return <div>
<strong>Total: $ {this.getTotal()}</strong>
<table id='orderlines' style={tableStyles}>
<tbody>
{this.getLines()}
</tbody>
</table>
</div>
}
getLines = () => {
return this.state.orderLines.map((item, _) =>
<OrderLine key={item.id} {...item} />)
}
}
Child component (OrderLine) has input (quantity) and method getTotal() which calculates the sum for this line
getTotal = () => (this.props.product.price * this.state.quantity).toFixed(2);
The goal is to calculate total sum for the Order.
I want to do something like sum(map(allOrderLines, (line) => line.getTotal())) but I can't get access to orderLine.getTotal() from the Order component.
So, what is the best way to do it? I know how to update parent's state (give callback function as prop) from child, but is it possible to do it from parent?
Full example here: