Reputation: 569
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>
Upvotes: 0
Views: 901
Reputation: 1983
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;
}
Upvotes: 1