0

I have a contentEditable div where I am trying to update the colors of words that the user types into it onChange. When I detect a word that I want to be colored, I wrap it in a <span> element.

The issue is, the <span> elements aren't being properly rendered, and the raw HTML of the span elements are being displayed like this:

bla bla bla <span class="text-primary">keyword with color</span> bla bla bla.

How do I fix this? Is this something to do with React?

This is the code I'm using to generate the text that goes inside the contentEditable div. I store the result in a variable in render() and directly pass it into the contentEditable div with {text}.

function formatDateKeywords(name, keyword) {
  var startIndex = name.indexOf(keyword);
  var endIndex = startIndex + keyword.length;
  var res =
    name.substring(0, startIndex) +
    "<span class='text-primary'>" +
    keyword +
    "</span>" +
    name.substring(endIndex, name.length);

  return res;
}

This is what the div looks like:

<div
    contentEditable="true"
    suppressContentEditableWarning={true}
    id="addItemInput"
    data-placeholder={placeholder}
    className="form-control text-left editable"
    type="text"
    onInput={(e) => this.handleInput(e)}
    onKeyDown={(e) => this.keyPress(e)}
>
    {formattedText}
</div>
Jasper Huang
  • 501
  • 2
  • 7
  • 15
  • You can find your answer here https://stackoverflow.com/questions/16625618/javascript-change-color-of-text-and-background-to-input-value – ESCoder Jun 13 '20 at 09:55
  • Can you provide the code, which you have run to change the color of text, so that it would be easy to resolve your issue ? – ESCoder Jun 13 '20 at 10:09
  • I don't want to change the color of the whole contentEditable div element, just specific words inside it. That's why I'm wrapping the words in , but alas the span elements aren't getting rendered correctly. – Jasper Huang Jun 13 '20 at 10:53

1 Answers1

1

in reactjs you have to use JSX to add tag into content: i use React.Fragment to avoid adding unused tag.

function formatDateKeywords(name, keyword) {
  var startIndex = name.indexOf(keyword);
  var endIndex = startIndex + keyword.length;
  var res = <>
        {name.substring(0, startIndex)}
        <span class='text-primary'>{keyword}</span>
        {name.substring(endIndex, name.length)}
    </>;

  return res;
}
Mahdi Aslami Khavari
  • 1,755
  • 15
  • 23