Created
November 27, 2017 07:47
-
-
Save brien-crean/62ff649a71fee0c916ccdbf6259081ba to your computer and use it in GitHub Desktop.
React component with Intersection Observer API
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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