How to open a link via "router.push" in a new tab using Nextjs router from next/navigation
Asked Answered
P

3

10

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>
Pipette answered 23/11, 2023 at 7:43 Comment(0)
P
-2

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>
Porte answered 23/11, 2023 at 7:58 Comment(3)
Ok but I am using a button instead of a Link otherwise I know Link would work. If you can find me a solution for Button other than what I found that would be great.Pipette
You can wrap your link around a button thenPorte
Because you'd usually don't want to use side effect like window.open it's a bad practice you better use cleaner ways like target=_blankPorte
D
5

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.

Dry answered 16/8 at 13:15 Comment(0)
P
-2

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>
Pipette answered 23/11, 2023 at 7:53 Comment(0)
P
-2

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>
Porte answered 23/11, 2023 at 7:58 Comment(3)
Ok but I am using a button instead of a Link otherwise I know Link would work. If you can find me a solution for Button other than what I found that would be great.Pipette
You can wrap your link around a button thenPorte
Because you'd usually don't want to use side effect like window.open it's a bad practice you better use cleaner ways like target=_blankPorte

© 2022 - 2024 — McMap. All rights reserved.