Generating HTML string from React component in background, using string is dangerous SetInnerHTML in another React component

I am trying to convert LaTeX strings to a React project. Although I am using react-mathjax

React components , I want to get an HTML string from LaTeX strings in order to concatenate it and other strings and set it to the dangerous SetInnerHTML.

My current code that I have tried

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

  • LaTeX strings are defined as strings
  • Make the DOM empty aDom

    on document.createElement('span')

    (in the background, not in the document's DOM tree).
  • Display LaTeX string ReactDOM.render

    inaDom

  • After rendering, get a string aDom.innerHTML

    or.outerHTML

Problem

The value aDom.innerHTML

(or .outerHTML

) is equal "<span><span data-reactroot=\"\"></span></span>"

(almost empty) although it aDom

has a perfect tree generated by MathJax.

Short,

  • aDom

    : 🙆
  • aDom.outerHTML

    : 🙅

Screenshot of console.log aDom

andaDom.outerHTML

Question

How can I get the "correct" HTML string from aDom

above?

+3


source to share


2 answers


Everything seems to work fine if you want to render any component to an HTML string:



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

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

      

+6


source


From what I can see, you are getting what you expect to get.

Given a root element ( aDom

in your case), ReactDOM will render its root component inside that element, and that component component will have an attribute data-reactroot

.

So what you see is the way it should be. From what I've tested there should be an inner tree as well.



var Another = React.createClass({
  render: function() {
    return (
      <div>Just to see if other components are rendered as well</div>
    );
  }
});

var Hello = React.createClass({
  render: function() {
    return (
      <div id="first"> 
        <div id="sec-1">Hello</div>
        <div id="sec-2">{ this.props.name }</div>
        <Another />
      </div>
    );
  }
});

var a = document.createElement('div');

ReactDOM.render(
  <Hello name = "World" /> ,
  a
);

console.log(a.outerHTML);
      

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
      

Run codeHide result


Result in console:

<div><div data-reactroot="" id="first"><div id="sec-1">Hello</div><div id="sec-2">World</div><div>Just to see if other components are rendered as well</div></div></div>

      

+3


source







All Articles