2

My code:

addEmoji = () => {
    document.getElementById('description-text').focus();

    let element = $("#span").clone()[0];
    let sel = window.getSelection();

    if (sel.getRangeAt && sel.rangeCount) {
        let range = sel.getRangeAt(0);
        range.deleteContents();
        range.insertNode(element);

        let textNode = document.createTextNode('\u00A0');
        range.setStartAfter(element);
        range.insertNode(textNode);
        range.setStartAfter(textNode);
        range.collapse(true);

        sel = window.getSelection();
        sel.removeAllRanges();
        sel.addRange(range);
    }
}

render() {
    return (
        <div>
            <form onSubmit={this.onSubmit}>
                <div id="description-text" ref="description" suppressContentEditableWarning="true" contentEditable={true} />                    
                <div>
                    <button type="submit">Guardar Cambios</button>
                </div>
            </form>
            <div>
                {this.state.emojiPanel ? 
                    <div>
                        <button type="button" onClick={this.switchEmojiPanel}>Hide Emojis</button>
                        <Picker onClick={this.addEmoji} set='emojione' emojiSize={26} title="Select Emoji" color="#000" /> 

                        <span id="span">INSERT</span>
                    </div>
                    :
                    <div>
                        <button type="button" onClick={this.switchEmojiPanel}>Select Emojis</button>
                    </div>
                }
            </div>
        </div>
    )
}

The problem is that when trying to insert the span in the div when the user clicks an emoji, window.getSelection() does not acquire the value of my position in the div since I am calling the function from another component, which is the Picker, then the span is always inserted at the beginning of the div.

If someone could help me with this, I would really appreciate it !!

1 Answers1

0

You can use the css user-select property to achieve this. Style the elements you are clicking on inside the Picker component with user-select: none; property.

This way when user clicks an emoji inside the Picker component, the caret position or text selection are going to stay where you left it at your contentEditable div.

Be sure to check compatability to make this work properly across different browsers: https://developer.mozilla.org/en-US/docs/Web/CSS/user-select