0

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

6
  • 2
    Why would you want to render unsafe HTML? Is it safer to know what word/character(s) to highlight, and simply highlight them in-place? Or can you show us what you've tried at the very least? Commented Oct 23, 2022 at 9:21
  • How are you generating that array of strings? Would it be possible to change it to containe JSX elements? i.e. ["Te", <span>x</span>, "t"] ? Commented Oct 23, 2022 at 9:27
  • possibly: Highlight text using ReactJS Commented Oct 23, 2022 at 9:33
  • @Terry I just wanted to get highlighting tool perfect for my usage, so I tried to make one. I need to highlight, on certain action focus on certain highlight, and load the data to/from DB. Commented Oct 23, 2022 at 10:12
  • @amer my own algorithm that sticks <span> before selection and </span> after it. Commented Oct 23, 2022 at 10:13

1 Answer 1

3

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" }} />

Sign up to request clarification or add additional context in comments.

2 Comments

What do you mean by "sanitize"?
Sanitization basically means removing potentially harmful things from html. There are tons of libraries and APIs that do that. wikipedia.org/wiki/HTML_sanitization

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.