Use Anchors with React-Router

Using anchor tags in react-router 4

It is a known issue with react router. (https://github.com/ReactTraining/react-router/issues/394#issuecomment-220221604)

There is a solution as well. https://www.npmjs.com/package/react-router-hash-link this package solves the issue.

You have to use this Hash Link as the Link like below.

import { HashLink as Link } from 'react-router-hash-link';

React router anchor link

I solved it by getting helps from this question
How to get history on react-router v4?

Here is my code

document.getElementById("test").onclick = function(e){
e.preventDefault();
history.push("/page2")
}

and it's working!

https://codesandbox.io/s/inspiring-goldberg-utryd?fontsize=14&hidenavigation=1&theme=dark

ReactJS: Go to anchor link in HTML with react router dom

Perhaps you could use Element#scrollIntoView() to mimic the default browser behavior of anchor link.

For instance, if <Updates /> is the component that hosts your patch note content (where anchor links are defined), then you could run this function when <Updates /> is mounted or started to achieve this:

function scrollToHash() {

/* Obtain hash from current location (and trim off leading #) */
const id = window.location.hash.substr(1);

if(id) {
/* Find matching element by id */
const anchor = document.getElementById(id);

if(anchor) {
/* Scroll to that element if present */
anchor.scrollIntoView();
}
}
}

/* Usage example */
function Updates() {

React.useEffect(() => {
scrollToHash();
},[]);

/* Render patch content that contains anchors */
return <div> ... </div>
}

ReactJS: Go to anchor link in HTML with react router dom only after the full page load

I think the idea would be to use an effect to scroll to the appropriate component after the component mounts. Perhaps something like this:

React.useEffect(() => {
const anchor = window.location.hash.slice(1);
if (anchor) {
const anchorEl = document.getElementById(anchor);
if (anchorEl) {
anchorEl.scrollIntoView();
}
}
}, []);

Notes:

  • I haven't tested this.
  • useLayoutEffect instead of useEffect may give a better experience here; see this article for details.
  • I'm bypassing React and using the DOM. I usually try to avoid that, but since this logic is isolated and inherently focused on browser DOM behavior, I think this is a good use case for it (instead of complicating the code by pulling in more interactions with your React components.)
  • scrollIntoView is convenient but experimental; consider using the scroll-into-view-if-needed NPM package instead.


Related Topics



Leave a reply



Submit