Adding target="_blank" to a link when using stateToHTML()
I am using draft-js-anchor-plugin to insert anchor tags into my content. I am setting the linkTarget option to _blank to set target="_blank":
this.linkPlugin = createLinkPlugin({
theme: {
input: classes.input,
inputInvalid: classes.inputInvalid,
link: classes.link
},
linkTarget: '_blank'
});
This works well in the editor. If I inspect a link in the debugger, I can see
<a
class="TextEditBase-link-1060"
title="http://archfirst.org"
href="http://archfirst.org"
target="_blank"
rel="noopener noreferrer"
>
<span data-offset-key="5uoh0-1-0"><span data-text="true">website</span></span>
</a>
However when I convert the content to HTML using stateToHTML(), the target="_blank" gets lost:
<p>My <a href="http://archfirst.org">website</a>.</p>
Here's my code:
getHtml = () => {
const contentState = this.state.editorState.getCurrentContent();
return stateToHTML(contentState);
};
How can I get target="_blank" in my HTML output?
I don't mind ditching the linkTarget option in draft-js-anchor-plugin, as long as I can somehow insert target="_blank" in all my anchor tags.
Please let me know if there is a better place to ask this question. I also asked the question on StackOverflow. Thanks in advance.
Have you tried using
let options = {
entityStyleFn = entity => {
const entityType = entity.get('type').toLowerCase();
if (entityType === 'link') {
const data = entity.getData();
return {
element: 'a',
attributes: {
target: data.targetOption,
href: data.url
}
};
}
}
}
stateToHTML(contentState, options)
Have you tried using
let options = { entityStyleFn = entity => { const entityType = entity.get('type').toLowerCase(); if (entityType === 'link') { const data = entity.getData(); return { element: 'a', attributes: { target: data.targetOption, href: data.url } }; } } } stateToHTML(contentState, options)
How can I add inner Text for the anchor tag?
Have you tried using
let options = { entityStyleFn = entity => { const entityType = entity.get('type').toLowerCase(); if (entityType === 'link') { const data = entity.getData(); return { element: 'a', attributes: { target: data.targetOption, href: data.url } }; } } } stateToHTML(contentState, options)How can I add inner Text for the anchor tag?
@ahamed just set the inner HTML in the following manner,
dangerouslySetInnerHTML={{ __html: <output from statetohtml()> && <output from statetohtml()>.replace(/href/g, `target='_blank' href`) }}