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>
)
}
4
Answers
You need to recursively compute the sum from both
Data
&SummedValue
components.The
Data
component holds value in its state via props.The
SummedValue
component needs to iterate over its children & compute the sum ofData
components directly & recursively handles the nestedSummedValue
components.SummedValueContext
is created to pass the summed value up the tree.useContext(SummedValueContext)
is used to get the parent’s summed value updater function.The
SummedValueContext.Provider
is used to provide the local summed value updater function to its children.Here is the impelement code for above functionality:
As we know Context passes through intermediate components while Using and providing context from the same component. The sample code below follows the same principle, please see the output below prior to proceeding with the code.
Note : This is a naive code, please see the another answer, the code in it is handling the known edge cases as well.
Please take advantage of the comments enclosed in the code.
App.js
Optimised implementation:
For a naive implementation, please see the another answer.
Note : Please take advantage of the comments enclosed in the code.
Output:
App.js
To solve this problem,
Pass a ref from the parent SummedValue component to its child SummedValue components. This allows us to access the computed value from the child components when they are nested. By using React’s useRef(), we can store and reference the computed values within SummedValue.
Explicitly pass the summedValueRef as a prop to each SummedValue child. This allows the parent SummedValue to access the calculated value of any nested SummedValue component and include it in its own total sum.