How to add target="_blank" to links in block-content-to-react?
Perfect! Since you're using block-content-to-react, you'll need to customize how links are rendered by adding a custom serializer for the link mark.
Here's how to make all links in your blog posts open in a new tab:
Add a custom serializer to your BlockContent component with the following code:
import BlockContent from "@sanity/block-content-to-react"
const serializers = {
marks: {
link: ({ children, mark }) => (
<a href={mark.href} target="_blank" rel="noopener noreferrer">
{children}
</a>
),
},
}
// Then use it in your component:
<BlockContent
blocks={yourContent}
serializers={serializers}
/>The key parts here are:
target="_blank"makes the link open in a new tabrel="noopener noreferrer"is important for security - it prevents the new page from having access to your page'swindowobject
If you want to conditionally control which links open in new tabs (some internal links stay in the same tab, external links open new tabs), you could add a boolean field to your link annotation schema in Sanity Studio, then check that value in your serializer like:
link: ({ children, mark }) => (
<a
href={mark.href}
target={mark.blank ? '_blank' : '_self'}
rel={mark.blank ? 'noopener noreferrer' : undefined}
>
{children}
</a>
),Note: @sanity/block-content-to-react is deprecated. When you have time, consider migrating to the newer @portabletext/react library, which uses a similar pattern but with a components prop instead of serializers.
Show original thread4 replies
Sanity – Build the way you think, not the way your CMS thinks
Sanity is the developer-first content operating system that gives you complete control. Schema-as-code, GROQ queries, and real-time APIs mean no more workarounds or waiting for deployments. Free to start, scale as you grow.