Skip to content

Instantly share code, notes, and snippets.

@brien-crean
Created November 27, 2017 07:47
Show Gist options
  • Save brien-crean/62ff649a71fee0c916ccdbf6259081ba to your computer and use it in GitHub Desktop.
Save brien-crean/62ff649a71fee0c916ccdbf6259081ba to your computer and use it in GitHub Desktop.
React component with Intersection Observer API
// simple react component to demonstrate intersection observer API usage
// renders box in red when fully visible otherwise renders in blue
import React, { Component } from 'react';
class Box extends Component {
constructor(props) {
super(props)
this.state = {
prevRatio: 0.0,
}
}
componentDidMount() {
this.createObserver();
}
createObserver = () => {
let observer;
let options = {
root: null,
rootMargin: "0px",
threshold: 1
};
observer = new IntersectionObserver(this.handleIntersect, options);
observer.observe(this.$box);
};
handleIntersect = (entries, observer) => {
entries.map((entry) => {
if (entry.intersectionRatio > this.state.prevRatio) {
this.$box.style.backgroundColor = `red`;
} else {
this.$box.style.backgroundColor = `blue`;
}
this.setState({ prevRatio: entry.intersectionRatio });
});
};
render() {
return (
<div ref={(box) => { this.$box = box; }} className="Box">
</div>
);
}
}
export default Box;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment