How to add a toggle to a link in the Portable Text editor in Sanity.io
5 replies
Last updated: Jan 4, 2023
W
Hi, I added a to the link. Can anybody tell me how to go about this? I think this needs to be done in a serializer function.
isExternaltoggle to a link in the Portable Text editor. I like to use this to add
target='_blank' rel='noreferrer, noopener'
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
W
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
W
I may need to use @portabletext/to-html...?
Jan 3, 2023, 11:38 PM
W
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
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.