1- import React , { useState , useMemo } from 'react' ;
2- import useIntersectionObserver from './useIntersectionObserver ' ;
1+ import React , { useState , useMemo , useCallback , useRef } from 'react' ;
2+ import { useInView } from 'react-intersection-observer ' ;
33
44const useRootMargin = offset => {
55 return `-${ offset * 100 } % 0px -${ 100 - offset * 100 } % 0px` ;
66}
77
88const useProgressRootMargin = ( direction , offset , node , innerHeight ) => {
9- if ( ! node ) return '0px' ;
10- const offsetHeight = ( node . offsetHeight / innerHeight ) ;
9+ if ( ! node . current ) return '0px' ;
10+ const offsetHeight = ( node . current . offsetHeight / innerHeight ) ;
1111 if ( direction === 'down' ) return `${ ( offsetHeight - offset ) * 100 } % 0px ${ ( offset * 100 ) - 100 } % 0px` ;
1212 return `-${ offset * 100 } % 0px ${ ( offsetHeight * 100 ) - ( 100 - ( offset * 100 ) ) } % 0px` ;
1313}
@@ -32,26 +32,33 @@ const Step = props => {
3232
3333 const rootMargin = useRootMargin ( offset ) ;
3434
35- const [ node , setNode ] = useState ( null ) ;
35+ const ref = useRef ( null ) ;
3636 const [ isIntersecting , setIsIntersecting ] = useState ( false ) ;
3737
38- const [ entry ] = useIntersectionObserver ( {
38+ const { ref : inViewRef , entry} = useInView ( {
3939 rootMargin,
4040 threshold : 0 ,
41- nodeRef : node ,
4241 } ) ;
4342
4443 const progressRootMargin = useMemo (
45- ( ) => useProgressRootMargin ( direction , offset , node , innerHeight ) ,
46- [ direction , offset , node , innerHeight ]
44+ ( ) => useProgressRootMargin ( direction , offset , ref , innerHeight ) ,
45+ [ direction , offset , ref , innerHeight ]
4746 ) ;
4847
49- const [ scrollProgressEntry ] = useIntersectionObserver ( {
48+ const { ref : scrollProgressRef , entry : scrollProgressEntry } = useInView ( {
5049 rootMargin : progressRootMargin ,
5150 threshold : progressThreshold ,
52- nodeRef : node ,
5351 } ) ;
5452
53+ const setRefs = useCallback (
54+ ( node ) => {
55+ ref . current = node ;
56+ inViewRef ( node ) ;
57+ scrollProgressRef ( node )
58+ } ,
59+ [ inViewRef , scrollProgressRef ] ,
60+ ) ;
61+
5562
5663 React . useEffect ( ( ) => {
5764 if ( isIntersecting ) {
@@ -82,7 +89,7 @@ const Step = props => {
8289
8390 return React . cloneElement ( React . Children . only ( children ) , {
8491 'data-react-scrollama-id' : scrollamaId ,
85- ref : setNode ,
92+ ref : setRefs ,
8693 entry,
8794 } ) ;
8895} ;
0 commit comments