Noel Tock
Noel Tock

Reputation: 609

How to parse mixed content into React components?

I'm ingesting content from an API which sends through HTML which also has third-party template tags. An example could be:

<h1>Title<h1>
<p>This is some content.</p>
[Tag]Other content[/Tag]
<p>More random content.</p>

If it wasn't for the template tags, I could just put everything through dangerouslySetInnerHTML, however I'd like to be able to separate the content inside of [Tag]...[/Tag] (square brackets, not HTML) into its own React component along the lines of <Tag content={content} />.

How would I be able to go about parsing out that component whilst then concatenating all the pieces back together?

Thank you!

Upvotes: 0

Views: 134

Answers (1)

Giang Le
Giang Le

Reputation: 7054

I think you can use renderToString for this case

import { renderToString } from 'react-dom/server'
...
const template = `<h1>Title<h1>
<p>This is some content.</p>
[Tag]Other content[/Tag]
<p>More random content.</p>`

const html = template.replace(/\[Tag\].+\[\/Tag\]/, renderToString(<Tag content={content} />))

Upvotes: 1

Related Questions