use-eventual-scroll

Hook that scrolls to an element after that element is added to the DOM

Downloads in past

Stats

StarsIssuesVersionUpdatedCreatedSize
use-eventual-scroll
111.3.04 years ago4 years agoMinified + gzip package size for use-eventual-scroll in KB

Readme

use-eventual-scroll

Hook that scrolls to an element after that element is added to the DOM



!CIci-badge !versionversion-badgepackage !downloadsdownloads-badgenpmtrends !Total downloadstotal-downloadstotal-downloads !MIT Licenselicense-badgelicense !PRs Welcomeprs-badgeprs !Code of Conductcoc-badgecoc
!Watch on GitHubgithub-watch-badgegithub-watch !Star on GitHubgithub-star-badgegithub-star

Table of Contents

- useEventualScroll

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.8react-hooks, 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