Goal: I want to convert strings including React components into fully-functional JSX.
The easier example, for which there are many solutions on Stack Overflow, is this:
render()
{
let txt = "<span><b>Hello World!</b></span>";
return <div dangerouslySetInnerHTML={{__html: txt}}></div>;
//---OR---
return ReactHtmlParser(txt); //using react-html-parser
//---OR---
return parse(txt); //using html-react-parser
}
But if instead, let txt = "<MyComponent/>";
, where MyComponent is a custom React component, I cannot find a way for the browser to interpret that correctly.
Using some methods, it will enter the DOM as lowercase <mycomponent><mycomponent/>
. With other tricks, I can get it into the DOM as uppercase <MyComponent><MyComponent/>
. But the browser will not interpret MyComponent as a React component, and will not execute the code inside.
I'm not interested in the answer React.createElement()
because I don't want to use this for one component at a time. I want to parse long strings of JSX.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…