Hello,
I have multiple occurrences where I link to specific sections of my app. Sadly, linking to them with a hash (
Thanks
Try this solution: #816
@frenzzy Should we pick this into master?
It works like a charm, thanks @frenzzy! I'd love to see this merged :)
@frenzzy @langpavel
Hello, i am loading some html code from db with dangerouslySetInnerHTML.
In this code i have got hash tag, for example something like this
<a href="#test"></a>
<p id="test">Some text</p>
When i click a tag, in first place it go to p tag and again to top.
Using debugin in this part of client.js
debugging
let scrollX = 0;
let scrollY = 0;
const pos = scrollPositionsHistory[location.key];
if (pos) {
scrollX = pos.scrollX;
scrollY = pos.scrollY;
} else {
const targetHash = location.hash.substr(1);
if (targetHash) {
const target = document.getElementById(targetHash);
if (target) {
scrollY = window.pageYOffset + target.getBoundingClientRect().top;
}
}
}
location is equal to
{
hash:#test,
key:undefined,
pathname:/page1
search:" "
state:undefined
} and pos
{
scrollX:0,
scrollY:0;
}
any suggestion?
How about something like this?
const Example = props =>
<div
dangerouslySetInnerHTML={{ __html: `
<a href="#test"></a>
<p id="test">Some text</p>
` }}
onClick={event => {
if (event.target.tagName === 'A') {
const link = event.target
const href = link.getAttribute('href')
if (href.charAt(0) === '#') {
const target = document.getElementById(href.substr(1))
if (target) {
event.preventDefault()
const rect = target.getBoundingClientRect()
const scrollX = 0
const scrollY = window.pageYOffset + rect.top
window.scroll(scrollX, scrollY)
}
}
}
}}
/>
Using mozilla-firefox and micrsoft edge without this part of code u mentioned, it is working it go to p tag with id test,and also when i reload the page with path /example#test it still go there.
But chrome and opera have same behaviour it go to p tag and again to top.
With ur code it just go a little down. and by using 2 or 3 hashlinks its go to same place (a little down)
const hmtlRaw = `
<a href="#test"></a>
<a href="#test1"></a>
<a href="#test2"></a>
<p id="test">Some text</p>
<p id="test1">Some text</p>
<p id="test2">Some text</p>
`
It should work in all browsers, try demo: https://jsfiddle.net/frenzzy/e09szjye/
Yes i see, it is also working without click event too i fiddle. I will search more.
But for some reason it is rerendering i think,, cause on hashlink click it go immediatly to p tag
and starting server side rendering and back to top.
@Shadowman4205:
But for some reason it is rerendering i think,,
No reason — except you didn't use <Link …> or something similar?
Most helpful comment
Try this solution: #816