Skip to content

Instantly share code, notes, and snippets.

@mereskin-zz
Last active August 29, 2015 13:57
Show Gist options
  • Save mereskin-zz/9533786 to your computer and use it in GitHub Desktop.
Save mereskin-zz/9533786 to your computer and use it in GitHub Desktop.
React in web components

Using react in components

Using react in components is actually quite straightforward. Be aware, that there is no easy way to insert a tag with a hyphen in JSX. So your react component should not contain any custom-elements inside.

my-component.html

<script src="./bower_components/versal/runtime.js"></script>
<script src="./bower_components/react/react.js"></script>
<script src="./dist/my-component.js"></script>

src/my-component.js

/** @jsx React.DOM */
(function(){
  var ReactComponent = React.createClass({
    render: function(){
      return <p>Hello, {this.props.name}!</p>
    }
  });

  // Versal is defined in versal/runtime.js
  Versal.registerElement('my-component', {
    createdCallback: function(){
      // Read props from attributes
      var props = reduce.call(this.attributes, function(props, attr){
        props[attr.name] = JSON.parse(attr.value);
        return props;
      }, {});

      // pass callback to react component
      props.onSomethingHappened = this.onSomethingHappened.bind(this);

      this._reactComponent = ReactComponent(props);
      React.renderComponent(reactToolbar, this);
    },
    
    attributeChangedCallback: function(name, old, current){
      var patch = {};
      patch[name] = current;
      _reactComponent.setProps(patch);
    },

    onSomethingHappened: function(foo){
      // do something
      this.dispatchEvent(new CustomEvent('somethingHappened', { detail: foo }));
    }
  });
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment