For a recent project I needed to be able to render React components (or really, just React-like components) into plain HTML strings. Of course, React provides a mechanism to do this: renderToStaticMarkup in its
ReactDOM library. But wow, that library is a really big dependency to import if I don’t want any of the DOM reconciliation stuff.
Also, it turns out I don’t even need React lifecycle events for my project. I don’t need component state either. I just want to render a bunch of stateless components with props and children. Something like this:
Well, maybe there’s a way to just import part of the rendering engine… but then I realized I had yet another requirement: I need to be able to modify the string version of every component as it is created. I can’t do that with React. I need a custom renderer.
Happily, with some experimentation I learned that it’s not that hard to create one! Below you can see my version of
renderToString(). It accepts both stateless functional components and component classes.
Of course, the version below is a bit naive. I’m certain there’s many edge cases of rendering which it does not cover, and like I said above, it does not support state or lifecycle events at all. That said, it works very well for my own purposes and I learned a lot about how React components are put together in the doing!
The following also includes a full test suite to show how it works.