Making an HTML string from a React component in background, how to use the string by dangerouslySetInnerHTML in another React component

Nyoho picture Nyoho · Apr 23, 2017 · Viewed 27.2k times · Source

I'm trying to render LaTeX strings in a React project. Although I use the react-mathjax React components, I want to get an HTML string made from the LaTeX strings in order to concatenate it and the other strings and set it by dangerouslySetInnerHTML.

My current code I tried

Sample code is here: https://github.com/Nyoho/test-react-project/blob/component2string/src/components/tex.jsx

  1. LaTeX strings are given as strings
  2. Make an empty DOM aDom by document.createElement('span') (in background. not in the document DOM tree.)
  3. Render a LaTeX string by ReactDOM.render into aDom
  4. After rendering, get a string by aDom.innerHTML or .outerHTML

Problem

The value of aDom.innerHTML (or .outerHTML) is "<span><span data-reactroot=\"\"></span></span>" (almost empty) although aDom has a perfect tree that MathJax generated.

Briefly,

  1. aDom: 🙆
  2. aDom.outerHTML: 🙅

A screenshot console.log of aDom and aDom.outerHTML

Question

How can I get the 'correct' HTML string from aDom above?

Answer

wrdevos picture wrdevos · Oct 31, 2017

This seems to work just fine if you want to render any component to a HTML string:

import { renderToString } from 'react-dom/server'

renderToString() {
  return renderToString(<MyAwesomeComponent some="props" or="whatever" />)
}