Updated post with a working example in CodeSandbox
We're using DraftJS to insert an <a>
around some selected text in an editor.
Original state
It presently works by wrapping the anchor tag around the highlighted text.
E.g., for this text:
Foo bar foo
.
If the user highlights "bar", our editor will render <a href='http://...'>bar</a>
The current code to alter the content state:
this.applyLink = () => {
const { editorState } = this.state;
const selectionState = editorState.getSelection();
const entity = Entity.create("LINK", "MUTABLE", {
url: "http://foo.com"
});
const update = RichUtils.toggleLink(editorState, selectionState, entity);
this.onChange(update);
};
The actual Link that is getting rendered:
const Link = props => {
const { url } = props.contentState.getEntity(props.entityKey).getData();
return (
<a href={url} style={styles.link}>
{props.children}
</a>
);
};
The custom decorator which creates the Link:
function findLinkEntities(contentBlock: ContentBlock, callback, contentState) {
contentBlock.findEntityRanges(character => {
const entityKey = character.getEntity();
return (
entityKey !== null &&
contentState.getEntity(entityKey).getType() === "LINK"
);
}, callback);
}
Desired state
Our product owner has asked that the links retain any other elements which may be selected.
E.g., for text with a custom entity:
Foo bar <custom-entity .../> foo
.
If the user highlights "bar" and the custom entity, we want to render the anchor tag around both of them. I.e. <a href='http://...'>bar <custom-entity .../> </a>
.
However, our code is stripping anything that isn't text-- the <custom-entity>
disappears.
Update with CodeSandbox
I've created an example which reproduces this in CodeSandbox, available here
The CodeSandbox page detail the steps to reproduce. In short if you add text and the Custom Entity (using the button), then highlight the content like so:
Then with that highlight still active, click 'Apply link', the editor renders:
^ Note the Custom Entity disappeared after the Link was applied.
Can anyone help figure out how to keep that Custom Entity inside the anchor tag?