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>
3
  • You can find your answer here stackoverflow.com/questions/16625618/… Commented Jun 13, 2020 at 9: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 ? Commented Jun 13, 2020 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 <span>, but alas the span elements aren't getting rendered correctly. Commented Jun 13, 2020 at 10:53

1 Answer 1

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;
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.