Embed React Into Your Old Ugly HTML

asdf
2 min readJul 15, 2018

Sometimes you don’t work on a greenfield project. Sometimes you inherit an old application (sometimes from your past self), that serves HTML plus jQuery and reloads the whole page on every action.

But you don’t like this approach (anymore), you want to play with React, Redux, GraphQL and all that cool new stuff.

That was our case at LidskaSila.cz. We had a system writen in the good old PHP, with many dashboards, tables, forms…

We decided to use React for new components, but we couldn’t go the SPA way with one root application element. Instead, we wrote a short piece of code, that allowed us to embed components into any place in the HTML document.

For example, if you put this code in a page, it renders the component Hello with these props into that div (given the Hello component exists and is exposed):

Simplest naive implementation could look like this:

The real production-ready code gets more complicated (shouldn’t use querySelector, should provide error handling, props should be optional, consider sharing the store etc.), but the basics remain:

  1. List components that could be embedded this way.
  2. For each element with the data-embed-component attribute, render the desired component.

I can’t share the code we actually used (I don’t work there anymore) and I currently don’t have a use case for this, so I will not implement it again.

But I find it worth sharing anyway, as an idea.

--

--

asdf

Developer, currently working on frontend at Mews