0

How can I navigate to an element from another page? I've tried this approach with react-scroll -->

import { Link } from "react-scroll";

const RightNav = ({ open, page }) => {

  return (


    <>

      <ul open={open}>
        <li> {page !== 'contactus' ? <Link to="benefits" smooth={true} delay={0} duration={400}>Benefícios</Link> : <Link to="/#benefits">Benefícios</Link>} </li>

        <li> {page !== 'contactus' ? <Link to="team" smooth={true}>Equipe</Link> : <Link to="/">Equipe</Link>} </li>
        <li> {page !== 'contactus' ? <Link to="location" smooth={true}>Localização</Link> : <a href="/#benefits">Localização</a>} </li>
        <li> {page !== 'contactus' ? <Link to="footer" smooth={true}>Contato</Link> : <a href="/#footer">Contato</a>} </li>
        <button>Entrar</button>
      </ul>
    </>
  );
};

But I didnt get much success. The main thing is that when I navigate outside the "/" index route, like "/contactus" I lost reference of those id sections and it throws me scroller.js:57 target Element not found.

Thanks!

  • How are you doing the routing? Is it happening on the back-end, or on the front-end with something like react-router? – Attila Sep 09 '20 at 20:17
  • Hi, sorry for delaying, I've used `import { Link } from 'gatsby';` its almos the same thing as Link of React. I'm navigating to /contactus and them I lost the reference of the section id (benefits for example) in the index page – Guibrother32 Sep 10 '20 at 12:55
  • 1
    You can pass your section ID from the source page to the `contactus` page. See the docs for details on how to do that: https://www.gatsbyjs.com/docs/gatsby-link/#pass-state-as-props-to-the-linked-page. Once you've navigated to the target page, you can use that ID with `scroller` from `react-scroll` (for example) to scroll to the specific element on mount—you can read the docs for that here: https://github.com/fisshy/react-scroll, they have good examples set up as well (for example, this one: https://codesandbox.io/s/basic-6t84k?file=/src/index.js:143-151) – Attila Sep 10 '20 at 22:40

1 Answers1

0

For those who are facing the same trouble, I've give up on react-scroll and implemented react router hash link instead. Worked properly, here's their npm package website -> https://www.npmjs.com/package/react-router-hash-link

  • Nice, that package even supports custom links so you can use it with Gatsby! Although, just to add on to this, `react-scroll` doesn't take into consideration any external linking, and anyone using that library would have to code that themselves—there isn't anything wrong with `react-scroll` per se. – Attila Sep 15 '20 at 17:13