React Base Fiddle (JSX)
Starting point for creating JSFiddles with React.
HTML
<script src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<div id="container">
<!-- This element's contents will be replaced with your component. -->
</div>
CSS
.example {
width: 400px;
height: 90vh;
background-color: red;
border: 1px solid black;
}
Babel + JSX
class Hello extends React.Component {
constructor(props) {
super(props)
this.isInViewPort = this.isInViewPort.bind(this)
this.handleScroll = this.handleScroll.bind(this)
}
componentDidMount() {
console.log(this.isInViewPort()) // false for second element - last in viewport
if (this.isInViewPort()) {
console.log("I'm in viewport!");
}
window.addEventListener('scroll', this.handleScroll);
}
componentWillUnmount() {
window.removeEventListener('scroll', this.handleScroll);
}
isInViewPort() {
const element = this.refs[this.props.id];
const rect = element.getBoundingClientRect();
const windowHeight = window.innerHeight || document.documentElement.clientHeight;
const result = rect.top <= windowHeight && rect.top + rect.height >= 0;
return result;
}
handleScroll() {
if (this.isInViewPort()) {
console.log("I'm in viewport!");
}
}
render() {
return (
<div className="example" ref={this.props.id} onClick={this.handleScroll} />
)
}
}
class App extends React.Component {
render() {
return (
<React.Fragment>
<Hello id={1} />
<Hello id={2} />
<Hello id={3} />
</React.Fragment>
);
}
}
ReactDOM.render(
<App />,
document.getElementById('container')
);