React - Parse HTML string and insert components at specific places within it

I am working on an app for a customer who wants to display Zendesk support article data with richer content than API / tool support. The API, based on Zendesk's basic WYSIWYG editor, is capable of serving an HTML block with <p>

and <img>

and tags <a>

. But it cannot, say, easily embed a video, show an image gallery, or link to another location in the app without requiring a hard update.

So we decided to create a small amount of DSL syntax through which the client could print something that would be parsed in our application and turned into richer content. For example:

[[ video src="youtube.com/whatever" ]]

      

can be disassembled in our application and replaced by attaching iframe

this video directly to the article.

The above example works great for me using all sorts of fun / problematic RegExp magic.

I know that parsing HTML with RegExp is the main anti-pattern and I will get around it without parsing HTML as such - I'm just looking for [[...]]

).

Basically, I parse each code, determine what to replace, pass that component back in, and then call ReactDOMServer.renderToString(replacementEl)

to insert the resulting HTML into the HTML line of the article, which is then displayed on the page using dangerouslySetInnerHtml

.

This works great despite all the obvious clutter issues. (I know, but the customer wants a very feature rich solution and wants to use the Zendesk API).

Here's the problem: This solution only works when rendering HTML . It doesn't work when I try to render like <Link>

(from React Router) or a homemade component <Gallery />

.

So I am trying to figure out if there is a good way to do this. One that does not ideally imply full RegExp padding on an HTML blog (which is clearly a mess ).

I guess the solution would involve removing the codes, converting the no-code HTML string to actual React components (as opposed to just spitting the string into another element), and then based on some book where shortcodes go into this new React component by inserting content into the page.

But I would appreciate some suggestions if anyone encounters a similar problem. I want to do it in such a way that it is not completely crazy and fragile, although obviously it was a messy problem.

EDIT . To clarify, when I say this doesn't work, I mean the JavaScript associated with React components won't run. If I replace the code with <Link to="whatever" />

, for example, it ReactDOMServer.renderToString

successfully turns this component into its last HTML (tag <a>

), but nothing happens when that tag is clicked, because the JavaScript that actually changes browserHistory

on normal click just doesn't run.

So perhaps the more poignantly asked question is:

Is there a way to inject React Components into an HTML string in such a way that they keep their JavaScript functions and not just become HTML?

+3


source to share





All Articles