react-scrollspy icon indicating copy to clipboard operation
react-scrollspy copied to clipboard

Cant link directly to a hash from outside the page

Open areknow opened this issue 1 year ago • 1 comments

Describe the bug I expect that this link https://32jhvk.csb.app/sample2#section-a3, would bring me to section a3, but when the page loads, the first section is visible. It should be on section 3.

To Reproduce Steps to reproduce the behavior:

  1. Go to https://32jhvk.csb.app/sample2#section-a3
  2. Notice that it is on the first section, instead of third

Expected behavior I expect the page to load, and then scroll to the hash in the url

areknow avatar May 06 '24 20:05 areknow

@areknow Thank you for your feedback.

First, please let me know if your case is urgent. For example, you are already using the component in production and your client or visitors complain.

Do you have any idea how you would like to use this featue?

  • Embedding hash handling in the component would be a bad idea, because the component can occur more than once on a page.
  • So I would suggest a named export, with the problem being that offsetTop, offsetLeft and behavior props have to be passed repeatedly as function arguments.

Here is a sketch of the implementation.

  useEffect(() => {
    const handleHash = ({ offsetTop = 0, offsetLeft = 0, behavior = 'smooth' }) => {
      const id = window.location.hash.slice(1);
      const content = document.getElementById(id);
      const container = document.scrollingElement || document.documentElement;

      if (content && container) {
        container.scrollTo({
          top: content.offsetTop - container.offsetTop - offsetTop,
          left: content.offsetLeft - container.offsetLeft - offsetLeft,
          behavior,
        });
      }
    };

    handleHash({ offsetTop: 80 });
  }, []);

toviszsolt avatar May 07 '24 04:05 toviszsolt

@areknow I was hoping you had already seen my reply.

toviszsolt avatar May 23 '24 11:05 toviszsolt

The issue is abandoned, so I'm closed it.

toviszsolt avatar Jun 10 '24 14:06 toviszsolt