Contentful logo

Contentful Community

Adding a data attribute to a hyperlink

Hey all,

I have an issue with formatting a link in my application. I am using the method documentToHtmlString and I pass in the options like this:

{
      renderNode: {
        [INLINES.HYPERLINK]: (node, next) => {
          console.log(node);

          let value = node.content[0]['value'];
          let uri = node.data.uri;

          return `<a class="test" href="${uri}" data="test" category="contact" data-category="contact" data-action="email" target="_blank">${value}</a>`;
        },
      },
    }

The problem I have is that the renderer ignores most of the attributes. Infact, the only ones it uses is class, href and target. All others are ignored. Does anyone know why?

Hi @jaymie.jeffrey, I think it’s possible that React might consider the additional non-standard attributes as dangerous, therefore stripping them from the output. You might want to look at this thread: https://stackoverflow.com/questions/54083103/contentful-documenttohtmlstring-doesnt-include-embedded-image-in-rich-text

A possible solution would be the last one about using dangerouslySetInnerHTML to print the <a> tag with your custom attributes.