DEV Community 👩‍💻👨‍💻

Eduardo Milpas
Eduardo Milpas

Posted on

Invoke a child function from the parent one to get computed data

Ok, let's say we have the most basic component, a <div> element with two inputs:

enter image description here

And let's call this component Card; There is also a 2nd component called CardHolder which consists of a div element containing Card components(a list of names and scores).

Let's say we want the CardHolder component to print at the button the average of all the scores in its list, like in the image below:

enter image description here

How can this be implemented considering the following constraints?:

1) Use of functions(No Classes)
2) Card Element is independent(does not require any external information to work) and reusable(any component can import it and use it without any knowledge of its internals and there is no need to the caller to send props/states to the Card child)
3) Keep it simple, ie: do not recommend global state handlers(ie: Redux), that'd be like to use a building to kill an ant, let's remember the goal here is to keep a simple component with a very basic functionality.

My background is java, and there the easiest way to achieve this is creating a public function in card(ie: getScore()) so the parent(no matter who is it) just need to invoke it without knowledge of how does it work on the inside; Is this feasible in any similar way in react or what is the right approach/pattern in here?

Thanks to anyone in advance...

Top comments (0)

We want your help! Become a Tag Moderator.
Check out this survey and help us moderate our community by becoming a tag moderator here at DEV.