R. Kohlisch
R. Kohlisch

Reputation: 2993

Reach-Routers navigate() with an offset for anchor links?

Is there a way to do

navigate('/#about')

with reach-router, but with an offset of, say, -16px? I haven't been able to find anything on that.

Upvotes: 0

Views: 844

Answers (2)

kimberrypi
kimberrypi

Reputation: 131

You can pass a state to the link like so:

...

navigate(
    "/#about/",
    {
        state: { offset: "-16px" },
    }
)

...

and then access the state from the destination component. You can pass it to any part of that component.

Read more about this here: https://www.gatsbyjs.org/docs/gatsby-link/#add-state-to-programmatic-navigation

Upvotes: 1

Michiel
Michiel

Reputation: 353

Another solution could be to listen to route changes and call scroll(0, -16); if the url contains the anchor. See https://developer.mozilla.org/en-US/docs/Web/API/Window/scroll. Maybe calling scroll after calling navigate is enough.

Upvotes: 0

Related Questions