Created
May 13, 2020 20:26
-
-
Save balazsorban44/d697630ca03c1f5e885d51454afb7dfe to your computer and use it in GitHub Desktop.
Scrolls to an element after that element is added to the DOM
This file contains hidden or 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
import * as React from "react" | |
/** Scrolls to an element after that element is added to the DOM */ | |
const useEventualScroll = ( | |
/** | |
* Holds the element to scroll to. | |
* The closer it is to that element, the less Mutations are observed | |
* by MutationObserver. If not defined, document will be used. | |
*/ | |
container?: null | HTMLElement | |
) => { | |
React.useEffect(() => { | |
if (!location.hash || container === null) { | |
return | |
} | |
const _container = container || document | |
const observer = new MutationObserver(() => { | |
const element = _container.querySelector(location.hash) | |
if (element) { | |
element.scrollIntoView() | |
observer.disconnect() | |
} | |
}) | |
observer.observe(_container, { childList: true, subtree: true }) | |
return observer.disconnect | |
}, [container]) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment