ReactJS on existing HTML

Wrapper to embed existing HTML in ReactJS component

by Guillaume DOUMENC

HTML

<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.24/browser.js"></script>
<script src="https://fb.me/react-dom-0.14.0.js"></script>
<script src="https://facebook.github.io/react/js/jsfiddle-integration-babel.js"></script>

<div id="container">
  <!-- This element's contents will be replaced with your component. -->
</div>

<div id="box1"><span style="font-weight:bold;">box1</span></div>
<div id="box2"><span style="font-style: italic;">box2</span></div>

JavaScript 1.7

var Wrapper = React.createClass({
  render: function() {
    return <div dangerouslySetInnerHTML = {
      {
        __html: this.props.html
      }
    }
    />;
  }
});

var Swapper = React.createClass({
  replace: function(id) {
    if (!(id in this)) {
      var node = document.getElementById(id);
      var span = document.createElement('span');
      span.appendChild(node.childNodes[0]);
      this[id] = span.innerHTML;
    }
    return this[id];
  },
  getInitialState: function() {
    return {
      swap: false
    };
  },
  onClick: function() {
    this.setState({
      swap: !this.state.swap
    });
  },
  render: function() {
    box1 = <Wrapper html={this.replace('box1')}/>;
    box2 = <Wrapper html={this.replace('box2')}/>;
    if (this.state.swap) {
      content = [box1, box2];
    } else {
      content = [box2, box1];
    };
    return <div>
    	{content}<button onClick={this.onClick}>Swap</button>
      </div>;
  }
});

ReactDOM.render( < Swapper / > , document.getElementById('container'));