skip to Main Content

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. please advice. thank you.

My code is like this right now:

import { useRouter } from "next/navigation";

const router = useRouter();

 <Button
          onClick={() => {
            router.push(`${mylink}`);
          }}
        >
          Order
</Button>

2

Answers


  1. Chosen as BEST ANSWER

    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>
    

  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>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search