Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 250
Nyoho Avatar asked Apr 23 '17 04:04

Nyoho


People also ask

How do you use dangerouslySetInnerHTML in React?

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.

Can you return a string from a React component?

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.

Can you use HTML and React together?

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.

How do I get the React component in 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.


1 Answers

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" />) } 
like image 193
wrdevos Avatar answered Sep 20 '22 16:09

wrdevos