If we want to know if a element is visible after scrolling in React, let's take look at the following sketch:
javascript<-- Webpage starts --> ······························· ▲ ▲ | | | pageYOffset | | | +--------------------------------------+ | | | Computer screen | ▼ | | ------------------------------ | ··· | | | | | ▲ | | | | | | | offsetTop | | Hello, | | | | | | I'm a webpage. | | | innerHeight | | | | | | | | | | | | | | | | | ▼ | | ------------------------------ | ··· | | | | +--------------------------------------+ | ▼ +----------------+ ................................... | Hidden element | +----------------+
The hidden element will be visible when:
terminalpageYOffset + innerHeight >= offsetTop;
Thus, we need to add a listener to check the condition on scrolling.
jsximport React, { useEffect, useRef } from 'react'; const App = () => { const hiddenRef = useRef(); useEffect(() => { window.addEventListener('scroll', scrollHandler); return () => window.removeEventListener('scroll', scrollHandler); }, []); const scrollHandler = () => { if(window.pageYOffset + window.innerHeight >= hiddenRef.current.offsetTop) console.log(`Hidden element is now visible`); } return( <div> <div style = {{height: `10000px`}}>Hello, I'm a webpage.</div> <div ref = {hiddenRef}>Hidden element</div> </div> ); } export default App;
Hi, I'm Erik, an engineer from Barcelona. If you like the post or have any comments, say hi.