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.
Sample code is here: https://github.com/Nyoho/test-react-project/blob/component2string/src/components/tex.jsx
aDom
by document.createElement('span')
(in background. not in the document DOM tree.)ReactDOM.render
into aDom
aDom.innerHTML
or .outerHTML
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,
aDom
: 🙆aDom.outerHTML
: 🙅A screenshot console.log of aDom
and aDom.outerHTML
How can I get the 'correct' HTML string from aDom
above?
dangerouslySetInnerHTML is a property that you can use on HTML elements in a React application to programmatically set their content. Instead of using a selector to grab the HTML element, then setting its innerHTML , you can use this property directly on the element.
React component can return only string, it's perfectly valid (and works as OP stated) ... but this use case is not supported. Using components to just return a string is not a good choice. It can be ineffective when you need many translated strings in one component.
By default, React does not permit you to inject HTML in a component, for various reasons including cross-site scripting. However, for some cases like a CMS or WYSIWYG editor, you have to deal with raw HTML.
To get HTML from a react component, you can use the ReactDOMServer. renderToString method (doc) used mainly for SSR purpose. However I guess you can achieve what you want with it.
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" />) }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With