Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add target="_blank" to all links in Draft.js content

Tags:

draftjs

I am trying to add target="_blank" to all the links in Draft.js content. I am new to this library, so my initial attempt is to simply iterate through all the entities and identify the LINK entities. However the entity map is coming up empty even though the content has a link in it. Here's my code:

getHtml = () => {
    const contentState = this.state.editorState.getCurrentContent();

    // entityMap shows as empty
    const entityMap = contentState.getEntityMap();
    console.log('entityMap', JSON.stringify(entityMap, null, 4));

    // stateToHTML() exports the anchor tag with href, but not target="_blank"
    return stateToHTML(contentState);
};

How do I iterate through all the entities and how do I insert target="_blank" when I find a LINK entity?

P.S. I am using version 0.10.5 of Draft.js.

like image 813
Naresh Avatar asked Oct 29 '25 01:10

Naresh


1 Answers

draft-js-export-html stateToHTML() allows you to pass an options argument to change the shape of your entity object. If you are ok with adding target='_blank' to all of your anchor tags you could do this:

...
let options = {
  entityStyleFn: (entity) => {
    const entityType = entity.get('type').toLowerCase();
    if (entityType === 'link') {
      const data = entity.getData();
      return {
        element: 'a',
        attributes: {
          href: data.url,
          target:'_blank'
        },
        style: {
          // Put styles here...
        },
      };
    } 
  }
};
return stateToHTML(contentState, options);
like image 90
MadEste Avatar answered Oct 31 '25 11:10

MadEste



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!