Linking to an element on same page OR to element from another page

I’m currently using scrollIntoView functionality, but I need this to link to specific components both from the same page, with smooth scrolling preferred, as well as the ability to navigate to the components from another page.

This is my first question, hopefully it’s not a repeat!

:wave: Hey @fitz - it might make it easier for us if you can post some working code or link to an example repo. Also, your question is not exactly clear :sweat_smile:. Is this working in the current page and you need to figure out how to do it from another page?

@PantheRedEye Sorry about that! My goal is to use a link in the header of my home page to link to a specific element by attribute, i.e. “About” link in the header will then scroll to the element with say an id=“about” on that home page. If possible I would love to have the route updated as well with #about, so that if that link is accessed directly, it opens to that spot on the page.

Right now I’m getting this functionality through a click handler, but this has no effect on the path & can’t be accessed except from the home page:

onClick={() => {
  const el = document.getElementById(
  if (el) window.scrollTo(0, Position(el))

@PantheRedEye does that make more sense? If you need more just lemme know.

Also, yes this works on the page, but doesn’t update the router & isn’t accessible from another page, which is my goal, so I’m assuming that updating the path will be necessary?

Hey @fitz - I have not done this, so I can only explore options with you. Using the methods from useLocation and navigate, maybe the approach here: javascript - How to add hash to url with React Router without rerendering? - Stack Overflow would work to update the route?

Also - I am not exactly certain what you mean by ‘isn’t accessible from another page.’ Is this a separate issue from setting the route and parsing the hash? Meaning - are you trying to link to an element that exists on a page that is not currently rendered in the dom?

Exactly - say I’m on the about page & I hit a link in the header that is to the info video on the homepage, I want the link to bring you to that part of the homepage. I’m thinking just build the logic into function that scrolls you down the page, so first it brings you to the homepage, then scrolls you to the correct section once loaded. I’m thinking this makes sense to put into the header’s pseudo link (really just a button)? Actually I can think of a few ways to do it, then have a listener on the home page that does something like:
if (path.contains('#')) extractIdAndScrollTo(path)

Got it working great! @PantheRedEye thank you!

1 Like