I want to have 2 functional React components:
-
a
Data
component that holds a value in state, that is passed through props: -
a
SummedValue
that also holds a value in state, but calculates this value as the sum of it’s children’s value, where its children can be eitherData
or otherSummedValue
components, nested arbitrarily
I would like to use them like this:<SummedValue> <Data value={3}/> <Data value={5}/> <SummedValue> <Data value={4}/> <Data value={1}/> </SummedValue>
Currently, in the SummedValue
component, I can get the data from Data
components alone by children.props.value
. However I dont know how to get this value from nested SummedValue
components, as it is not a prop.
Basically I think this is related to passing data from the child to the parent, but I cant find the configuration that works
function SummedValue({children}) {
// how can I access this computed value in parent component?
let computedValue = 0;
// Only works for props, not internal values
children.forEach(child => {
if (child.props.value) {
value += child.props.value
}
})
return(
<div>
<span>SUMMED NUMBER IS: {computedValue}
{children}
</div>
)
}
Many thanks for the help 🙂