Contentful logo

Contentful Community

Add a target="_blank" to hyperlink within Rich Text Content Type

Hello,

Does anyone know how to add a target="_blank" to hyperlinks within the Rich Text Content Type. I can’t see any options for opening a link in a new tab.

Cheers!

There’s no way to do this through the Contentful Web App. You can however do it when rendering rich text to HTML.

Check out this tutorial how to do this with JavaScript: https://www.contentful.com/developers/docs/javascript/tutorials/rendering-contentful-rich-text-with-javascript/#customized-rendering

Instead of overriding BLOCKS.PARAGRAPH, you’d override INLINES. HYPERLINK, test the url and then output different markup. That could look something like this:

const options = {
  renderNode: {
    [INLINES. HYPERLINK]: (node, next) => {
      return `<a href="${node.data.uri}"${node.data.uri.startsWith('https://mydomain.com') ? '' : ' target="_blank"'}>${next(node.content)}</a>`;
    }
  }
}

Perfect, this works great thanks. Using ‘next’ was giving me an error “next is not a function” (any idea why?) so I updated the code slightly and added a rel checker too.

import { INLINES } from '@contentful/rich-text-types'

const website_url = 'https://mydomain.com'

const options = {
  renderNode: {
    [INLINES.HYPERLINK]: (node) => {
      return <a href={node.data.uri} target={`${node.data.uri.startsWith(website_url) ? '_self' : '_blank'}`} rel={`${node.data.uri.startsWith(website_url) ? '' : 'noopener noreferrer'}`}>{node.content[0].value}</a>;
    }
  }
}

Thanks again :slight_smile: