Reveal on Scroll with Intersection Observer


Updated May 29th, 2023

Reveal on Scroll via Intersection Observer

Mdn docs here

Colby Fayock video here with link to the code in description

Used Apple’s website as an Example. Need useRef, useState, and useEffect hooks.

Little trickier than with vanilla JS. Access the DOM element with useRef hook. Can’t access inside render method itself we need to do so inside a useEffect with an empty dependency array.

  const observer = new IntersectionObserver((entries) => {
    const entry = entries[0]
    //console.log('entry', entry)
}, [])

By logging the entry to the console you can see we have access to an “isIntersecting” property that is initially false. This is what we will store in state with the useState hook.

Note: The “isVisible” property will not work as intended, visibility is a little less performant and is not needed for our use case.

Could create a custom hook to do all this for you or leverage the existing React-Intersection-Observer library and “useInView” hook:

npm install react-intersection-observer --save