Last active
August 19, 2021 16:31
-
-
Save rileybathurst/c71ade485281ebff1e5a9a07741bb0a2 to your computer and use it in GitHub Desktop.
React version of the MDN docs for IntersectionObserver tested in Gatsby, presume it works in default react
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
import React, { useState, useEffect, useRef } from 'react'; | |
// give me a background | |
const pageStyle = { | |
background: "palegreen", | |
height: "200vh", | |
} | |
// component | |
function Example() { | |
let boxElement = useRef(); | |
useEffect(() => { | |
console.log("boxElement", boxElement.current); | |
let box = boxElement.current; | |
createObserver(); | |
let prevRatio = 0.0; | |
function createObserver() { | |
let observer; | |
let options = { | |
threshold: buildThresholdList() | |
}; | |
observer = new IntersectionObserver(handleIntersect, options); | |
observer.observe(box); | |
} | |
// trust the math | |
function buildThresholdList() { | |
let thresholds = []; | |
let numSteps = 20; | |
for (let i=1.0; i<=numSteps; i++) { | |
let ratito = i/numSteps; | |
thresholds.push(ratito); | |
} | |
thresholds.push(0); | |
return thresholds; | |
} | |
function handleIntersect(entries, observer) { | |
entries.forEach((entry) => { | |
if (entry.intersectionRatio > prevRatio) { | |
setRatio(entry.intersectionRatio); | |
} else { | |
setRatio(entry.intersectionRatio); | |
} | |
prevRatio = entry.intersectionRatio; | |
}); | |
} | |
}); | |
const [ratio, setRatio] = useState(0.1); // I dont want to set a number here I want to query it */ | |
// starting style | |
const boxStyle = { | |
backgroundColor: `rgba(40, 40, 190, ${ratio})`, | |
border: "4px solid rgb(20, 20, 120)", | |
width: "350px", | |
height: "350px", | |
display: "flex", | |
alignItems: "center", | |
justifyContent: "center", | |
padding: "20px", | |
} | |
return ( | |
<div id="box" style={boxStyle} ref={boxElement}> | |
<div className="vertical"> | |
Welcome to | |
<strong>{ratio}</strong> | |
</div> | |
</div> | |
); | |
} | |
const ObserverPage = () => { | |
return ( | |
<main style={pageStyle}> | |
<h1>Hey</h1> | |
<Example /> | |
</main> | |
) | |
} | |
export default ObserverPage; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
https://developer.mozilla.org/en-US/docs/Web/API/Intersection_Observer_API