I am using Draft.js for its mentions plugin. Sometimes, I want users to add a mention not by selecting an item from a dropdown but by writing something like, for example, "@item" or "@item".
As you can see in the function below, if I type a word that starts with @* or ends with * it becomes a mention automatically.
export const replaceString = (editorState, setEditorState) => {
const contentState = editorState.getCurrentContent();
const selectionState = editorState.getSelection();
const block = contentState.getBlockForKey(selectionState.getAnchorKey());
const blockAsArray = block.getText().split(' ');
const lastWord = blockAsArray.pop();
if (lastWord.startsWith('@*') || lastWord.endsWith('*') ) {
const currentSelectionState = editorState.getSelection();
const currentContent = editorState.getCurrentContent();
const contentStateWithEntity = currentContent.createEntity(
"MENTION",
"MUTABLE",
{ nature: 'remedy', lastWord}
);
const entityKey = contentStateWithEntity.getLastCreatedEntityKey();
const newContentState = Modifier.replaceText(
contentState,
selectionState.merge({
anchorOffset: currentSelectionState.getEndOffset() - lastWord.length,
focusOffset: currentSelectionState.getEndOffset()
}),
lastWord,
editorState.getCurrentInlineStyle(),
entityKey
);
setEditorState(EditorState.push(
editorState,
newContentState,
'replace-text'
))
} else {
setEditorState(editorState)
}
}
What I would love to do now is to insert this mention as a span that I can style. Is there a way I can do that?