Rendering React components from an HTML string

I'm getting an HTML string from an AJAX request, that looks something like that:

<div> <SpecialComponent/> <SecondSpecialComponent/></div>

What i need, is to be able use this string in a React component, as it were valid JSX.

I tried using the dangerouslySetInnerHTML as instructed in this discussion: how-to-parse-html-to-react-component

I've also tried React libraries like react-html-parse and html-react-parser . No success

When i was working with AngularJS(1), i was using some small directive that would take care of that situation. I need to achieve the same with React. Any ideas?

EDIT: if anybody is interested, i found a library that takes care of the issue: https://www.npmjs.com/package/react-jsx-parser


my suggestion is you do something like the following.

first set a state variable to equal the HTML you want to return

this.setState({html: response.data.html})

then in your return you can do the following

   return ( 
   {this.state.html} 
   );

You're not supposed to be doing things this way. Although React components look like html tags when using JSX, they are actually either classes or functions. What you're trying to do is equivalent to trying to parse:

"<div>document.write('foo')</div>"

You're literally mixing a javascript function name in string form with html markup in the same string. You will have to parse the string to separate the React component from the surrounding html markup, map the React components in string form to their actual React counterparts, and use ReactDOM.render to add the component to the page.

let mapping = [
    {"name":"<SpecialComponent/><SecondSpecialComponent/>","component":<SpecialComponent/><SecondSpecialComponent/>},
    {"name":"<someOtherComponent/><someOtherComponent/>","component":<someOtherComponent/><someOtherComponent/>}
];
let markup = "<div><SpecialComponent/><SecondSpecialComponent/></div>";
let targetComponent;

mapping.forEach((obj) => {if(markup.indexOf(obj.name)>-1){
    targetComponent=obj.component;//acquired a reference to the actual component
    markup.replace(obj.name,"");//remove the component markup from the string
    }
});

/*place the empty div at the target location within the page 
give it an "id" attribute either using element.setAttribute("id","label") or 
by just modifying the string to add id="label" before the div is placed in 
the DOM ie, <div id='label'></div>*/

//finally add the component using the id assigned to it

ReactDOM.render(targetComponent,document.getElementById("label"));

Never tried this before. I wonder if this will actually work :)

链接地址: http://www.djcxy.com/p/52160.html

上一篇: 尝试将redux整合到反应中。 Webpack对store.js感到窒息

下一篇: 从HTML字符串渲染React组件