'Draft-js get mention position in editorState currentContent
I'm using draft-js-mention-plugin and I'm looking for a method that returns the mention position in the whole text (without using indexOf()).
For exemple, I want to get the beginning and the ending positions of piRstone in this sentence :
Welcome to piRstone, our new colleague.
I'm supposed to get 11 for the beginning position and 19 for the ending.
<div className="editor">
<Editor
editorState={this.state.editorState}
onChange={this.onEditorChange}
plugins={plugins}
// placeholder={this.state.placeholder}
ref={(element) => { this.editor = element; }}
/>
<MentionSuggestions
onSearchChange={this.onSearchChange}
suggestions={this.state.suggestions}
onAddMention={this.onAddMention}
/>
</div>
Here is my onAddMention() method :
onAddMention(object) {
console.log(object);
}
Maybe there is an easier method to work with but the mentions plugin doc is a bit weak.
Solution 1:[1]
You will get the offset & length of particular mention in entityRanges object of the block, the offset will be the initial index & offset + length of your mention will be the last index
[
{
"key": "4p8mh",
"text": "Nice to meet you #name#",
"type": "unstyled",
"depth": 0,
"inlineStyleRanges": [],
"entityRanges": [
{
"offset": 20,
"length": 6,
"key": 0
}
],
"data": {}
}
]
By iterating over this object you will get offset & length
Object.keys(content.blocks).map(i => {
const {entityRanges, text} = content.blocks[i];
entityRanges.map((range, idx) => {
console.log(range.offset)
console.log(range.length)
});
});
Solution 2:[2]
In 2022 you can run these in your code to get mentions positions from editorState
const rawContentState = convertToRaw(editorState.getCurrentContent());
console.log(rawContentState) <---- this is an object with a key called blocks and key called entityMap. blocks has an entityRanges object with start and end points ;))
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Riddhi Patel |
| Solution 2 |
