draft-js-utils icon indicating copy to clipboard operation
draft-js-utils copied to clipboard

Change LINK to open in new tab

Open MikulasFrenak opened this issue 9 years ago • 6 comments

Hi mate, your work is very nice. I have problem... I use draft-js plugins and i want to change default LINK element that it after click open it in new tab. thanks

MikulasFrenak avatar Sep 09 '16 08:09 MikulasFrenak

+1. I render this link <a href="www.site.com" target="_blank">someLink</a> in my decorator. But after export target="_blank" was missing

optimatex avatar Sep 25 '16 11:09 optimatex

This is an old issue, so I don't know if you're still having this problem. But when you create the entity, if you set the target attribute to _blank, the resulting HTML (after calling stateToHTML) will use the target value and cause the link to open in a new tab.

Like so (during creation of the entity):

const contentStateWithEntity = contentState.createEntity(
  'LINK',
  'MUTABLE',
  {
    target: '_blank',
    url, // This could also be 'href'. Both are supported.
  }
);

You mentioned that you're using draft-js-plugins so you may not have this type of control during creation of the entity, but this may be helpful for anyone else with this issue.

jrubins avatar Jun 06 '17 16:06 jrubins

this solution worked for me + I think this issue can be marked as resolved 👌

willisplummer avatar Aug 02 '17 11:08 willisplummer

Just stumbled across this issue. I don't know how to apply the workaround shown above when using draft-js-anchor-plugin. That plugin is inserting target="_blank" correctly. However after applying stateToHTML() this attribute gets lost. Please see details in issue https://github.com/sstur/draft-js-utils/issues/128. Also see my question on StackOverflow. Any help would be much appreciated.

nareshbhatia avatar Feb 20 '18 06:02 nareshbhatia

Set in the options of stateToHTML a custom function ("entityStyleFn") that sets the target attribute:

        const options = {
            entityStyleFn: ( entity ) => {
                if ( entity.get('type').toLowerCase() === 'link' ) {
                    const data = entity.getData();
                    return {
                        element: 'a',
                        attributes: {
                            href: data.url,
                            target: data.targetOption
                        }
                    };
                } 
            }
        };

        stateToHTML( currentContent, options );

lucasbos avatar Aug 22 '18 08:08 lucasbos

Also having this issue. While the solution from @lucasbos works, this should be part of stateToHTML by default.

mskelton avatar Feb 19 '19 21:02 mskelton