Add target='_blank' to Portable Text links with isExternal toggle

5 replies
Last updated: Jan 4, 2023
Hi, I added a
isExternal
toggle to a link in the Portable Text editor. I like to use this to add
target='_blank' rel='noreferrer, noopener'
to the link. Can anybody tell me how to go about this? I think this needs to be done in a serializer function.
AI Update

You're on the right track! Yes, you'll need to customize how your links are rendered using a serializer/component. Here's how to do it:

For React Applications

If you're using @portabletext/react, you can create a custom mark component that checks for your isExternal field:

import { PortableText } from '@portabletext/react';

const components = {
  marks: {
    link: ({value, children}) => {
      const target = value?.isExternal ? '_blank' : undefined;
      const rel = value?.isExternal ? 'noreferrer noopener' : undefined;
      
      return (
        <a 
          href={value?.href} 
          target={target}
          rel={rel}
        >
          {children}
        </a>
      );
    },
  },
};

// Then use it like:
<PortableText value={portableTextContent} components={components} />

Schema Setup

Make sure your link annotation schema includes the isExternal field:

{
  name: 'link',
  type: 'object',
  title: 'Link',
  fields: [
    {
      name: 'href',
      type: 'url',
      title: 'URL',
    },
    {
      name: 'isExternal',
      type: 'boolean',
      title: 'Open in new tab',
      description: 'Open link in a new window',
    },
  ],
}

Then add it to your Portable Text field's annotations:

marks: {
  annotations: [
    {
      name: 'link',
      type: 'link',
    },
  ],
}

For Other Frameworks

The concept is similar across frameworks - you need to provide a custom serializer that reads the isExternal value from your annotation data and conditionally adds the target and rel attributes.

The key is that annotations in Portable Text are stored in the markDefs array, and your custom serializer receives the annotation's value object which contains all the fields you defined in your schema - including your isExternal boolean.

Show original thread
5 replies
You're correct, it would be handled in your serializer's components. What do you have set up so far?
I didn't find anything so I am guessing:
const imageUrl = require('@sanity/image-url');

const getSerializers = client => {
  // custom serializer for sanity blocks
  // read more: <https://www.sanity.io/docs/presenting-block-text>
  return {
    types: {
      code: ({node}) => '```' + node.language + '\n' + node.code + '\n```',
      mainImage: ({node}) => imageUrl(client).image(node).url(),
      image: ({node}) => `<img src="${imageUrl(client).image(node).url()}" alt="${node.alt}" id="${node.imageId}"/>`,
      slug: ({node}) => node.current,
      link: ({node}) => `<a href="${node.href}" ${node.isExternal && "target='_blank' rel='noreferrer, noopener'"}>${node.text}</a>`,
    }
  }
}

module.exports = getSerializers;
I may need to use @portabletext/to-html...?
I think I got it. For future reference:

const imageUrl = require('@sanity/image-url');

const getSerializers = client => {
  // custom serializer for sanity blocks
  // read more: <https://www.sanity.io/docs/presenting-block-text>
  return {
    types: {
      code: ({node}) => '```' + node.language + '\n' + node.code + '\n```',
      mainImage: ({node}) => imageUrl(client).image(node).url(),
      //image: ({node}) => `![${node.alt}](${imageUrl(client).image(node).url()}{:#${node.imageID})`,
      image: ({node}) => `<img src="${imageUrl(client).image(node).url()}" alt="${node.alt}" id="${node.imageId}"/>`,
      slug: ({node}) => node.current,
    },
    marks: {
      link: ({children, mark}) => `<a href="${mark.href}" ${mark.isExternal && "target='_blank' rel='noreferrer, noopener'"}>${children}</a>`,
    }
  }
}

module.exports = getSerializers;
Awesome! Thanks for letting us know you found a solution!

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?