-
Notifications
You must be signed in to change notification settings - Fork 2k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Persist scroll position in the Help Center
- Loading branch information
Showing
2 changed files
with
47 additions
and
1 deletion.
There are no files selected for viewing
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
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,34 @@ | ||
import { useEffect, useState } from '@wordpress/element'; | ||
|
||
/** | ||
* Persist the value in memory so when the element is unmounted it doesn't get lost. | ||
*/ | ||
let cachedScrollPosition = 0; | ||
|
||
/** | ||
* Persists the scroll position of an element in memory and returns it. | ||
* @param ref the HTML element to track the scroll position of. | ||
* @param enabled to only enable for article pages. | ||
* @returns the current or last recorded scroll position. | ||
*/ | ||
export function useArticleScrollPosition( ref: React.RefObject< HTMLElement >, enabled: boolean ) { | ||
const [ scrollPosition, setScrollPosition ] = useState( cachedScrollPosition ); | ||
|
||
useEffect( () => { | ||
const element = ref?.current; | ||
|
||
const handleScroll = () => { | ||
if ( element ) { | ||
setScrollPosition( ( cachedScrollPosition = ref.current.scrollTop ) ); | ||
} | ||
}; | ||
if ( enabled ) { | ||
element?.addEventListener( 'scroll', handleScroll ); | ||
} | ||
return () => { | ||
element?.removeEventListener( 'scroll', handleScroll ); | ||
}; | ||
}, [ ref, enabled ] ); | ||
|
||
return scrollPosition; | ||
} |