0

Hello this is my first time posting a question to stackoverflow so feel free to ask if you need more information.

I'm currently working in a React/Typescript project.

So I have a string where I only want a specific substring to be wrapped in a span element because I would be applying an italicization font style (For some reason, or does not work). Then convert that into a react element. For example I will have this long string and I just want the substring 'dog' to be wrapped in a span. So it would look like this:

I want a <span class="italicize-text">dog</span> really bad.

I currently have this function that will return it as a string.

const italicizeText = (text: String, subtext: string) => 
{return text.replace(subtext,'<span class="italicize-text">' + subtext + '</span>');};

The output looks like this:

'I want a <span class="italicize-text">dog</span> really bad.'

I want to convert the html string into a react element without using any libraries. My company discourages me from using any of the existing html string to react parsing libraries at the moment since they don't have much stars. Also to not use dangerouslySetInnerHTML.

I have tried https://www.npmjs.com/package/html-react-parser just to see if it does the trick and it does so if there's a simple way to replicate what they're doing, that'll be great!

Sophie
  • 103
  • 6
  • "since they don't have much stars" -- seriously? Company policy depends on the number of stars on GitHub? My suggestion is using `DOMPurify`. See this: https://stackoverflow.com/questions/29044518/safe-alternative-to-dangerouslysetinnerhtml – technophyle Nov 27 '20 at 19:21

1 Answers1

0

You can try to replicate it by writing a function that parses HTML into a parse tree and another that walks the parse tree and maps it into React. I’m certain that HTML parsers exist that will be suitable. The mapping to React could be built up as you go along.

Do your self a favor and write lots of unit tests.

duffymo
  • 305,152
  • 44
  • 369
  • 561