T
TanStack•3y ago
generous-apricot

How to handle hash from Link component

Hi guys, maybe someone can tell me how to handle hashes from Link hash prop? I didn't find any event for it. I'm using react-router beta 83
No description
1 Reply
generous-apricot
generous-apricotOP•3y ago
I found that I can get currentLocation from
const { state } = useRouter();
const { state } = useRouter();
The hash is changed by the react-router Link component, but is not updated in the state. It's still '/' I did the temporary solution, but still waiting for any info, how more correctly implement it via @tanstack/react-router
import { useEffect } from 'react';

import { useRouter } from '@tanstack/react-router';

export const useAnchorOnPage = (): void => {
const {
history: {
location: { pathname, href },
},
} = useRouter();

useEffect(() => {
const elementId = href.replace(pathname, '');

if (elementId.length !== 0) {
document.querySelector(elementId)?.scrollIntoView();
}
}, [href, pathname]);
};
import { useEffect } from 'react';

import { useRouter } from '@tanstack/react-router';

export const useAnchorOnPage = (): void => {
const {
history: {
location: { pathname, href },
},
} = useRouter();

useEffect(() => {
const elementId = href.replace(pathname, '');

if (elementId.length !== 0) {
document.querySelector(elementId)?.scrollIntoView();
}
}, [href, pathname]);
};
Because now it's just a workaround It's the same as scrollToTop after route change 🙂
export const route = new Route({
...
onLoaded: () => {
window.scrollTo(0, 0);
},
});
export const route = new Route({
...
onLoaded: () => {
window.scrollTo(0, 0);
},
});
Looks weird

Did you find this page helpful?