0

I need a default href value for Next/Link, as we do in plain html like below

<a href='#' ></a>

I tried this to Link but it reloads the page, if I keep it empty it produces some error because its required attribute

<Link href='#'></Link>

Actually I am mapping a collection where some items does not have href so I need to put it blank and show some alert on click;

MVP
  • 83
  • 3
  • 9

2 Answers2

2

Conclusion

If you are using dynamic routing,

<Link href=":"></Link>

will fix your issue.

Explanation

Next.js only prefetches href if the link is local.

When the href does not starts with "/", "?", or "#", Next.js constructs URL and checks if the URL is external or not.

const resolved = new URL(url, locationOrigin)
return resolved.origin === locationOrigin && hasBasePath(resolved.pathname)

When you pass empty string as href, Next.js thinks the link targets local URL, thus tries to prefetch the page, and fails if you have dynamic routing.

When you use : as href in <Link>, Next.js disables prefetch and fixes the issue. Although using : seems weird, it's actually recognized as a invalid "script" by the browser which should be ignored.

Though Next.js provides prefetch option, prefetch still occurs when you hover the link element even if you specify prefetch={false}, which causes the issue.

Toshimichi
  • 46
  • 1
  • 7
0

If you use <Link href=''></Link> it won't produce any error, since it has its required attribute and its value is equal to ''.

fsefidabi
  • 153
  • 1
  • 12
  • but it produces some error on click like 'The provided `href (/products/[product]) value is missing query values (product) to be interpolated properly.` – MVP Oct 06 '21 at 05:28
  • Yeah, I see now. It happens when we have nested routes. Can't you use `router.push` instead? This is similar to your problem: [https://stackoverflow.com/questions/65469874/link-component-interpolation-error-nextjs](https://stackoverflow.com/questions/65469874/link-component-interpolation-error-nextjs) – fsefidabi Oct 06 '21 at 05:58
  • That's not exactly what I want, It should have some default value as we used to handle anchor tag in html – MVP Oct 06 '21 at 06:04
  • You can't do this. Whatever value that you set as default value will be considered as a **query**. The default value (similar to the anchor tag in HTML) works for cases that do not contain queries. So you should check the existence of `[product]` before using the `` tag and if it exists, pass the `/products/[product]` to `href`. – fsefidabi Oct 06 '21 at 06:12