I think the simplest way for you in React 16 would be using an intersection observer (like react-intersection-observer
) and a couple of refs(or you could use some dedicated packages).
The code would be something among these lines:
import React, {useRef} from 'react';
import { useInView } from 'react-intersection-observer';
export default props => {
const refToScroll = React.useRef();
// be sure to check out all the options available
const [refFromScroll, refFromScrollVisible] = useInView();
useEffect(() => {
// as soon as refFromScroll is visible, your scroll logic fires
if(refFromScrollVisible && refToScroll.current) {
// add more options as you like
refToScroll.current.scrollIntoview({behavior: "smooth"})
}
}, [refFromScrollVisible, refToScroll.current]);
return (<div>
{/*as soon as it is visible your scrolling logic will be executed*/}
<div ref={refFromScroll} />
{/*your other components*/}
{/*scroll to this div*/}
<div ref={refToScroll} />
</div>)
}
You could use any other similiar package (react-use-visibility
) or even write your own hook or component which will call element.getBoundingClientRect()
, detect if any of its properties (top
,left
,bottom
, right
) are positive and less than windows height
and width
(assuming you are looking to check if it's visible at all, you can totally use another element as visibility boundary) and fire a callback or fill flag once it's visible (see this question for reference). Personally I like react-intersection-observer
the most since it's react-tuned and pretty customizable on top of that.