use-eventual-scroll
TypeScript icon, indicating that this package has built-in type declarations

1.3.0 • Public • Published

use-eventual-scroll

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


CI version downloads Total downloads MIT License PRs Welcome Code of Conduct

Watch on GitHub Star on GitHub


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

Dependents (0)

Package Sidebar

Install

npm i use-eventual-scroll

Weekly Downloads

8

Version

1.3.0

License

MIT

Unpacked Size

20.5 kB

Total Files

13

Last publish

Collaborators

  • balazsorban