Reputation: 111
I'm working on a text highlighting and I was able to detect selection etc. Now I have something like
Te<span>x</span>t
in a string and
["Te", "<span>", "x", "</span>", "t"]
In an array. How can I render this using react in a safe way? DangerouslysetinnerHTML doesn't work here by the way (maybe needs a hook or something, but it's unsafe so, better to use something else).
*The amount of these spans can change so there may be a lot of tags.
Edit: My algorithm makes a mask (an array full of zeros) for a text and whenever user selects something it adds 1 to certain fields in array (like an interval). Then it parses the text and the mask, and when for example 01 occurs then it pastes the opening tag in between (and when 10 => closing tag). What's maybe other way of achieving Medium-like highlighting feature?
Thanks in advance
Upvotes: 0
Views: 978
Reputation: 12235
The dangerouslySetInnerHTML
is dangerous when you try to render user content with it. What I mean, it's not more dangerous to render string with <spans>
injected than the original string. If you want to sanitize the string, you could do it before highlighting.
<div dangerouslySetInnerHTML={{ __html: "Te<span>x</span>t" }} />
Upvotes: 3