use-eventual-scroll
Hook that scrolls to an element after that element is added to the DOM
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#fooconst App = const loading setLoading = /** * 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) */ return <div> loading ? "Loading..." : <p ="foo">Some text</p> </div>
Documentation
useEventualScroll
useEventualScrollref?: 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