Add target='_blank' to Portable Text links with isExternal toggle
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 thread5 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.