Next.js: Link component doesn't navigate properly when it has a hash fragment in it

Created on 15 Jun 2017  路  9Comments  路  Source: vercel/next.js

Reproductions:

Case 1:

You are in the home page and you click this link:

<Link href="/partners#retailers">Retailers</Link>
// Somewhere down the page
<a id="retailers" name="retailers" />

It will take you to the page, but will not scroll back to the top nor take you to the retailers anchor.

Case 2:

You are in the /partners page and you click this link:

<Link href="/partners#retailers">Retailers</Link>
// Somewhere down the page
<a id="retailers" name="retailers" />

It will not jump you to the retailers anchor that was placed further down.

good first issue bug

Most helpful comment

This is not an enhancement. This is a bug.

All 9 comments

@rclai - we had this issue and many others with <Link>.

The solution we came up with was to create our own <Link> component (we needed too for styling anyways) and use the Imperative methods on Router to solve our issues.

When we click on a Link component, the handler runs, and we do a simple check -

    if (href.match(/((^tel:)|(^mailto:)|(^http:\/\/)|(^https:\/\/)|#)/gm)) {
      return;
    } else if (!!window.MSInputMethodContext && !!document.documentMode) {
      window.location.href = url;
      return;
    }

The first makes it so any tel: , mailto:, external (http/https) and # link returns out of the handler early.

The second piece was to get around a IE11 bug where navigating between pages caused Styled JSX to not flush right and be unstyled. This may be resolved now.

Basically, anything that passed this part of our handler can then be handled by Next imperative router implementation.

    Router.push(url).then(() =>
      window.scrollTo(0, 0)
    );

We also did scrollTo(0,0) because of it not resolving to the top of the page when navigating.

This is not an enhancement. This is a bug.

@rclai: "Case 2" seems to be fixed in beta 3.0.1-beta18

@rclai True. This is bug.

Has this been fixed ? still getting this on 4.2

@EranM6 the issue is still open with no linked pull requests, so it has not been fixed yet :) feel free to give it a go 馃憣

@rclai this is working for me. Are you sure it is not working because you have a typo in <Link href="/partners#retailer"? (#retailer is missing an s)

This is working for me too.

Then I'm going to close the issue. Thanks @pablopunk @superbull 馃憤

Was this page helpful?
0 / 5 - 0 ratings

Related issues

havefive picture havefive  路  3Comments

renatorib picture renatorib  路  3Comments

rauchg picture rauchg  路  3Comments

DvirSh picture DvirSh  路  3Comments

sospedra picture sospedra  路  3Comments