0

I have links as follows:

www.foo.com/#my_hash

The problem is, is that when the user input this, the hash is not scrolled to / accessed. My temporary work around was to use a custom method, which waits 4 seconds to manually scroll.

client.scrollToHash = function(delay = 0, offset = 0) {
  window.setTimeout(() => {
    const hash = document.location.hash.slice(1);
    if(!hash) {
      return;
    }
    const element = document.getElementById(hash);
    if(!element) {
      return;
    }
    window.scrollTo({
      top: element.getBoundingClientRect().top - offset,
      behavior: 'smooth'
    });
  }, delay);
};

Is it possible to detect something like an on load event from the native DOM, instead of using a timeout?

I am using functional components.

Do react functional components have an easy way to let you know that the component has rendered?

I am confused how anchor hashes work in general as if they come in from the user / browser, there will always be a delay, as the page takes time to load.

I would prefer not to use another library, but accomplish this using the DOM, or React functionality if possible.

Can this be accomplished using useEffect()

k.m.
  • 21
  • 2
  • This can be a tricky thing to do with react, however there is an npm package for it that will handle scrolling to hash anchors on a page https://stackoverflow.com/questions/40280369/use-anchors-with-react-router – Brett East May 27 '22 at 22:55

0 Answers0