I have the following problem, I need to call a function from one component to the other.
I have the X component where it is verified when the user scrolls to the end of the site, when this happens you can do an action, be it an alert, a setState or whatever.
container.onscroll = function () {
let height = this.clientHeight;
let scrollHeight = this.scrollHeight;
let scrollTop = this.scrollTop;
if (height + scrollTop === scrollHeight) {
_this.setState({ display: 'loader'});
funcionupdate() <--
setTimeout(function(){ _this.setState({ display: 'hidden'}); }, 2000);
}
}
On the other hand, the Y component, in which there is a function update()
.
How can I execute the update()
component function Y
from the component X
?
You can do it by
Context
, for which the parent container must contain the function to execute when the scroll reaches down. In case of communicating components that are not even siblings, it would be very complex in this way. The best option to keep things simple is to implement the Observer design pattern in your application. This way you can establish communication between any group of components (not just two). You can use libraries for this like Postal.js , PubSub.js , MicroEvent.js or EventEmitter2 .Example
Note: the example uses the Postal.js library which in turn depends on lodash .