1

I have a React app, receiving the blog post data from external cms. The data is raw HTML as a string, like this:

<h1>hello</h1>
<img src="example.com/felan.jpg">
<p>some text</p>
<img src"example.com/another.jpg">
...

Now, I want to replace img HTML tag with a jsx component called Img (with capital I). I do it with:

let postContentOptimized = post.replace("img", "Img");

<article dangerouslySetInnerHTML={{ __html: postContentOptimized }} />

But it automatically converts Img to img (changes PascalCase).

I also tried with other component names, and it throws this error:

React will try to recreate this component tree from scratch using the error boundary you provided, ErrorBoundary.
Shahriar
  • 1,855
  • 2
  • 21
  • 45
  • You cannot do this. HTML and JSX are not interchangeable like this. Setting the inner HTML will do just that: set HTML, it will not treat it as JSX, PascalCase or not. – Brian Thompson May 10 '21 at 17:45
  • So how should I parse a string including jsx tags? – Shahriar May 10 '21 at 17:47
  • maybe this will help you: https://stackoverflow.com/questions/36104302/how-do-i-convert-a-string-to-jsx – Zion Ay May 10 '21 at 17:52

1 Answers1

0

I found a package called react-jsx-parser. Its documentation isn't straightforward, thus I skipped it the first time I found it. Here's how to do it if you're confused like me:

<JsxParser components={{ components used in your string }} jsx={the string you want to parse} />

example:

<JsxParser components={{ Img }} jsx="<Img src="hello.png /><p>hello</p>" />
Shahriar
  • 1,855
  • 2
  • 21
  • 45