How to useLink Component with passHref Prop in Next.js
In this approach, we are using Next.js’s Link component with the passHref prop and legacyBehavior to generate an anchor tag (<a>) that opens the link in a new tab when clicked. This method ensures proper handling of routing within Next.js while opening the link in a new tab.
Example: The below example uses Link Component with passHref Prop to open a link in a new Tab in NextJS.
//src/app/page.js
"use client";
import React from 'react';
import Link from 'next/link';
const NewTabLink = () => (
<>
<h1>Using Link Component with passHref Prop</h1>
<Link href="https://w3wiki.org" passHref legacyBehavior>
<a target="_blank">
Open in New Tab
</a>
</Link>
</>
);
export default NewTabLink;
Step to run the application: Now run the application with the below command:
npm run dev
Output:
How to open a link in a new Tab in NextJS?
Opening a link in a new tab in Next.js consists of using either the target=”_blank” attribute in an anchor (<a>) tag or using Next.js’s Link component with the passHref prop to ensure proper handling of routing while opening the link in a new tab. In this article, we will explore both these approaches with complete implementation.
Table of Content
- Link Behavior in Next.js
- Using Anchor Tag with target=”_blank”
- Using Link Component with passHref Prop