1

I've created a simple text editor and I've also created the possibility to add emojis. The problem is that when I click an emoji the emoji is added and visible, but the previous existing emojis are replaced with question marks. My contentEditable div is controlled, meaning that whenever an emoji is added it causes a re-render. I got this problem in the following if case of my algorithm:

childValue = childValue.substring(0, caretPosition) + emoji + childValue.substring(caretPosition + 1, childValue.length)

childValue isn't a state variable, it's value is used to update a constant variable that will be used to update the state variable representing the contentEditable's dangerouslySetInnerHTML property, the caretPosition is perfect.

Any ideas why I might have this issue?

Will Carter
  • 73
  • 10
  • Try escaping the emojis when they are added: https://stackoverflow.com/questions/48419167/how-to-convert-one-emoji-character-to-unicode-codepoint-number-in-javascript then you will get something like "1f600" which can be used in html like 😀 –  Apr 03 '21 at 00:35

2 Answers2

1

This solution from https://stackoverflow.com/a/59793087/14550434 combined with HTML escaping should do the trick:

var p = document.querySelector("p");
var childValue = "Some sample text";
var caretPosition = 5;
var emoji = "";

const emojiToString = (emoji) => 
  ` &#x${emoji.codePointAt(0).toString(16)}; `;

childValue = 
  childValue.substring(0, caretPosition) + emojiToString(emoji) +
  childValue.substring(caretPosition, childValue.length);

p.innerHTML = childValue;
<p></p>
0

I solved this issue. I figured out that 'substring' was messing everything up, so I did the following:

newChildValue = Array.from(childValue);

childValue = newChildValue.slice(0, caretPosition).join('') + emoji + newChildValue.slice(caretPosition).join('');

This way I avoid using 'substring' as Array.from(str) splits a string into individual unicode characters without breaking them between bytes.

Will Carter
  • 73
  • 10