DraftJS Modifier.insertText(): Insert Unicode
Asked Answered
E

1

6

I've list of emojis. Each of them has its own unicode. With Modifier.insertText(), I would like to insert them to the text.

_addEmoji(text) {
    const { editorState } = this.state;
    const selection = editorState.getSelection();
    const contentState = editorState.getCurrentContent();
    const txt = '&#x' + text + ';';
    let nextEditorState = EditorState.createEmpty();
    if (selection.isCollapsed()) {
      const nextContentState = Modifier.insertText(contentState, selection, txt);
      nextEditorState = EditorState.push(
        editorState,
        nextContentState,
        'insert-characters'
      );
    } else {
      const nextContentState = Modifier.replaceText(contentState, selection, text);
      nextEditorState = EditorState.push(
        editorState,
        nextContentState,
        'insert-characters'
      );
    }
    this.onChange(nextEditorState);
  }

I expect to see 😄 inserted to the editor but it displays row 😄 instead.

I've inserted <meta charset="utf-8" /> to <head /> and the list of emoji is rendered perfectly. The main problem is the draftjs editor displays raw unicode instead of the emoji.

Any thoughts to fix this? Thanks.

Educt answered 21/10, 2016 at 3:59 Comment(2)
So you have included the unicode in the HTML and now it works fine? What is the problem here?, I don't understand. – Gisele
The charset should be specified in the html document's head. Are you using a different charset? – Interstadial
V
4

Cause insertText will parse your & to &amp; with HTML encoding.

You should type the character directly there, or use String.fromCharCode.

e.g.:

Modifier.insertText(contentState, selection, πŸ˜„);

or

Modifier.insertText(contentState, selection, String.fromCharCode(0xd83d, 0xde04));

Cause

'πŸ˜„'.charCodeAt(0).toString(16); //d83d
'πŸ˜„'.charCodeAt(1).toString(16); //de04
Vineyard answered 9/3, 2017 at 17:0 Comment(0)

© 2022 - 2024 β€” McMap. All rights reserved.