✨Discover storytelling in the AI age with Pixar's Matthew Luhn at Sanity Connect, May 8th—register now

How to add a toggle to a link in the Portable Text editor in Sanity.io

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.
Jan 3, 2023, 10:55 PM
You're correct, it would be handled in your serializer's components. What do you have set up so far?
Jan 3, 2023, 11:05 PM
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;
Jan 3, 2023, 11:09 PM
I may need to use @portabletext/to-html...?
Jan 3, 2023, 11:38 PM
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;
Jan 4, 2023, 12:16 AM
Awesome! Thanks for letting us know you found a solution!
Jan 4, 2023, 12:23 AM

Sanity– build remarkable experiences at scale

Sanity is a modern headless CMS that treats content as data to power your digital business. Free to get started, and pay-as-you-go on all plans.

Was this answer helpful?