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
3 Answers
Reset to default 2a
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