import React, { Component } from 'react';
import { observer } from 'mobx-react';
@observer
export default class Observer extends Component {
constructor(props) {
super(props);
this.state = { visible: !window.IntersectionObserver };
this.io = null;
this.container = null;
}
componentDidMount() {
(window.IntersectionObserver
? Promise.resolve()
: import('intersection-observer')
).then(() => {
this.io = new window.IntersectionObserver((entries) => {
entries.forEach((entry) => {
this.setState({ visible: entry.isIntersecting });
});
}, {});
this.io.observe(this.container);
});
}
componentWillUnmount() {
if (this.io) {
this.io.disconnect();
}
}
render() {
return (
<div
ref={(div) => {
this.container = div;
}}
{...this.props}
>
{Array.isArray(this.props.children)
? this.props.children.map((child) => child(this.state.visible))
: this.props.children(this.state.visible)}
</div>
);
}
}