draft-js-utils
draft-js-utils copied to clipboard
Change LINK to open in new tab
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
+1. I render this link
<a href="www.site.com" target="_blank">someLink</a>
in my decorator. But after export target="_blank" was missing
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.
this solution worked for me + I think this issue can be marked as resolved 👌
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.
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 );
Also having this issue. While the solution from @lucasbos works, this should be part of stateToHTML by default.