简体   繁体   中英

NextJS Link href default value

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;

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.

如果你使用<Link href=''></Link>它不会产生任何错误,因为它有它的 required 属性并且它的值等于''

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM