react-scrollspy
react-scrollspy copied to clipboard
Cant link directly to a hash from outside the page
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:
- Go to https://32jhvk.csb.app/sample2#section-a3
- 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 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,offsetLeftandbehaviorprops 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 });
}, []);
@areknow I was hoping you had already seen my reply.
The issue is abandoned, so I'm closed it.