How to add target="_blank" to links in block-content-to-react?

4 replies
Last updated: Feb 9, 2022
How can I make a link in my blog post open in a new tab instead of the current tab? I am using block-content-to-react. I know I need to add
target="blank"
to the anchor tag, but I don't know how to do it using Sanity.
AI Update

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 tab
  • rel="noopener noreferrer" is important for security - it prevents the new page from having access to your page's window object

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 thread
4 replies
user U
, so from studio you would have to create an option to choose which link target you want to have (e.g. a boolean
blank
) and then on the frontend you can do something like this:
<Link href={href} target={blank ? '_blank' : '_self'}>
Thanks for your reply. I am new to sanity so I don't know how to create that option. And I don't think I need a boolean, I need all the links to be opened in a new tab. Do you know how I can do that?
I got it. I added the following to my serializer:
marks: {
   link: ({ children, mark }) => (
     <a href={mark.href} target="_blank" rel="noopener noreferer">
       {children}
     </a>
   ),
},
well done,
user U
!

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.

Was this answer helpful?