Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

dynamic HTML String to react component

I would be getting dynamic html content from my template rendering which was rendered by other react components. How would I convert this html string to React component so that I can use the component in my render function. Note that I want to preserve react specific attributes used for diffing.

React.createClass( {
  var self = this;

  componentWillMountDown : function() {
    //htmlString is essentially huge dynamic one in my actual case
    var htmlString = "<div class='classDiv' react-id="0.1"><input type='text'/></div>";
    self.setState({responseString : htmlString});
    self.forceUpdate();
  },
    
  render: function() {
    var Response = this.state.responseString;
    //how would I return the react component as response?
    return (<Response/>); //does not work. err is it shd be valid react component
   }
});

I've tried converting htmlString to HTMLDocument object and recursively creating React.createElement in willmount callback and setting react component. however, the error is type toUpperCase is not defined.

like image 498
Bharanidharan K Avatar asked Jun 08 '15 17:06

Bharanidharan K


People also ask

Can I convert HTML to React?

When you convert HTML website to ReactJS, you need to turn web pages into components. Furthermore, if you only have one page, you can create a folder called components under the SRC folder. Then, you need to create a single . JSX file there like index.

What is dangerouslySetInnerHTML React?

dangerouslySetInnerHTML. dangerouslySetInnerHTML is React's replacement for using innerHTML in the browser DOM. In general, setting HTML from code is risky because it's easy to inadvertently expose your users to a cross-site scripting (XSS) attack.


1 Answers

A few hours ago, I published an html-to-react module in npm (https://www.npmjs.com/package/html-to-react) that may help you.

Please let me know if there's anything you need, I can certainly work with you to make the module more flexible.

like image 195
Mike Nikles Avatar answered Oct 08 '22 21:10

Mike Nikles