Reputation: 130
On my React app, I have two pages: page A, the home page, and page B.
On page B, I have links that go to page A in a specific section.
On page A:
<section id="foo">Foo</section>
On page B:
<a href="/#foo">Go to foo</a>
Every time I go to page B from page A and click on the link, the screen goes to the last scroll position and not the section.
I tried to deactivate the browser scroll history function with:
useEffect(() => {
if (history.scrollRestoration) {
history.scrollRestoration = 'manual';
}
}, []);
I also to tried to add function to go to desired section:
useEffect(() => {
if (window.location.hash) {
const anchor = document.querySelector(window.location.hash);
anchor.scrollIntoView();
}
}, []);
But none of these solutions works. I reproduce the same behaviour on Chrome and Firefox.
Upvotes: 2
Views: 837
Reputation: 130
It was a Gatsby feature: it overrides the browser default scroll history behaviour. More info there https://www.gatsbyjs.com/docs/how-to/routing/scroll-restoration/
I fixed it by adding:
// gatsby-browser.js
exports.shouldUpdateScroll = ({
routerProps: { location },
getSavedScrollPosition,
}) => {
return location.href.indexOf("#") > -1 ? false : true;
};
Upvotes: 3