最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Nextjs Router.push vs href - Stack Overflow

programmeradmin1浏览0评论

For Routing to some page on click, I can achieve it in two ways

import Router from 'next/router'  

<button onClick={() => Router.push('/about')}>
    <a>Go to About</a>
</button>

And

 <button>
     <a href="/about">Go to About</a>
 </button>

Which one is the best practice in Nextjs?

For Routing to some page on click, I can achieve it in two ways

import Router from 'next/router'  

<button onClick={() => Router.push('/about')}>
    <a>Go to About</a>
</button>

And

 <button>
     <a href="/about">Go to About</a>
 </button>

Which one is the best practice in Nextjs?

Share Improve this question asked Dec 31, 2019 at 10:24 Midhun G SMidhun G S 9779 silver badges23 bronze badges 1
  • stackoverflow./questions/54968574/… – Mujahidul Islam Commented Dec 31, 2022 at 7:30
Add a ment  | 

3 Answers 3

Reset to default 2

a tag inside button is not allowed in semantic html, both of them are interactive elements.

For links, Next provides Link ponent that accepts a tag as a child. For buttons, use <button onClick={() => Router.push('/about')}>text</button> without a.

The best way to create links between pages is to use your nextjs package.

import Link from "next/link";

Then use it like that

<Link href={'/'} params={'id': 1}>
  <a>link</a>
</.Link>

if useing node js router href linked by name route

For the best user experience I would suggest a third option / best practice:

import Link from "next/link";

<Link href={"/within/your/page"} passHref>
  <button>go</button> // or any other element
</Link>

pre NextJS 10 if your path had dynamic segments you would need to pass "as" also like:

import Link from "next/link";

<Link href={"/review/[id]"} as={"/review/12"} passHref>
  <button>go</button> // or any other element
</Link>

The Link Component / the router.push enables client side navigation. This makes navigating your website a lot faster.

you can read more on this here:

  • https://nextjs/docs/api-reference/next/link
  • https://nextjs/docs/api-reference/next/router
发布评论

评论列表(0)

  1. 暂无评论