'Can HTML anchor tags ever be used for internal links in Gatsby?
I'm developing a website where a Search box can return a lot of results in a dropdown list and each result has a clickable internal link to a webpage within the same site.
I initially followed Gatsby's advice and implemented these as <Link>
elements, . However, this seems to be causing an issue when scrolling in the search results shortly after performing a new search - the scrollbar jumps back to the top of its own accord 3 or 4 times before then settling down afterwards. This is repeatable for the same search only after clearing the browser cache, which makes me suspect it is somehow related to Gatsby's pre-loading of pages.
If the links are changed to be HTML <a>
tags instead, the problem goes away... but am concerned that this is going against Gatsby's advice and there may be other issues I don't know about yet (haven't seen anything so far...)
Could anyone advise whether it is advisable to use anchor tags for internal links in these circumstances?
Solution 1:[1]
Of course, you can always use the standard <a>
tag for internal routing, however, you will be outside of React's scope (@reach/router
's scope). In your case, since you are not creating internal navigation per se (meaning navigation through internal pages) I think that your workaround is the lightest and most native approach, without adding extra dependencies which will increase the bundle size, with a functionality that can be handled natively.
As you said, <Link>
component is compiled into an <a>
tag with some React's vitamins in the end so, to me, it's the best approach.
Solution 2:[2]
Gatsby <Link>
Issue When Using Tailwind Elements offCanvas
I had a similar issue using Gatsby <Link>
inside an offCanvas component causing the page scroll to completly freezeon all devices untill navigating away. Guess the element using an event that conflicts with how the triggers.
Replacing all <Link>
tags that go to internal pages inside the component solve the problem. Refering to 'Ferren' answer, eventually tags with to
attributes compiled into tags with href
.
<div className={'offcanvas'} id={id} aria-labelledby={`#${id}Label`} tabIndex={-1}>
<div className={'offcanvas-header'}>
<a href={'/about'} className={'offcanvas-title'} id={'#offfcanvasLabel'}>
About Us
</a>
<button type={'button'} data-bs-dismiss={'offcanvas'} aria-label={'Close'} tabIndex={-1}></button>
</div>
...
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Ferran Buireu |
Solution 2 |