Reputation: 307
I am developing a Nextjs app and would want to direct user to another link using router.push
but I do not know how to open the link in new tab.
My code is like this right now:
import { useRouter } from "next/navigation";
const router = useRouter();
<Button
onClick={() => {
router.push(`${mylink}`);
}}
>
Order
</Button>
Upvotes: 14
Views: 23227
Reputation: 13599
Router.push is meant to be used to continue on the same tab to upload new content to that page. Try using window.open('www.yourdomain.com', '_blank');
instead.
Upvotes: 9
Reputation: 438
What router.push
does is a redirection to the route you defined. Here what you want is to open a new tab on a different link.
You can use NextJS Link and set the target as _blank
import Link from "next/link";
<Link href={mylink} target="_blank">Order</Link>
If you want a button you can do it like this
<Link href={mylink} target="_blank">
<Button>Order</Button>
</Link>
Upvotes: -3
Reputation: 307
I figured out the issue I had to use the code below and get it working for external links.
Best for internal links:
import { useRouter } from "next/navigation";
const router = useRouter();
<Button
onClick={() => {
router.push(`${mylink}`);
}}>
Order
</Button>
But for external links it is better to use window.open() like the code below.
<Button
onClick={() => {
window.open({mylink});
}}>
Order
</Button>
Upvotes: -2