2

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.

Jiang YD
  • 3,205
  • 1
  • 14
  • 20
piRstone
  • 336
  • 3
  • 16

2 Answers2

0

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)
         });
    });
Riddhi Patel
  • 221
  • 3
  • 8
0

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 ;))

KingJoeffrey
  • 303
  • 5
  • 16