Search code examples
reactjsnode.jsnext.jsrouternextjs-dynamic-routing

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


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>

Solution

  • 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>