use-eventual-scroll
v1.3.0
Published
Hook that scrolls to an element after that element is added to the DOM
Downloads
8
Maintainers
Readme
Table of Contents
Installation
This should be installed as one of your project dependencies
:
yarn add use-eventual-scroll
or
npm install --save use-eventual-scroll
NOTE:
use-eventual-scroll
only works with react >=16.8, since it is a hook.
Usage
If you have to render some content in React that takes some time, but it holds an element you want to scroll to, you can use this hook to wait for the element to appear in the DOM, and initiate the scroll afterwards.
Example:
import useEventualScroll from "use-eventual-scroll"
// url: http://example.com#foo
const App = () => {
const [loading, setLoading] = useState(false)
useEffect(() => {
const someAsyncOperation = async () => {
//...
setLoading(true)
}
someAsyncOperation()
}, [])
/**
* By only adding this one line,
* the scroll to #foo will happen, even
* if it takes several 100 ms.
* (In which case navigating to this page for the first time
* would result in no scroll)
*/
useEventualScroll()
return (
<div>
{loading
? "Loading..."
: <p id="foo">Some text</p>
}
</div>
)
}
Documentation
useEventualScroll
useEventualScroll(ref?: HTMLElement | null): void
useEventualScroll
uses MutationObserver under the hood. By default, it listens to every change on document
. Optionally, you can pass an HTMLElement
reference to useEventualScroll
, to only care about changes inside that DOM element. It can increase performance.
LICENSE
MIT