Skip to content

Instantly share code, notes, and snippets.

@treshugart
Created August 28, 2017 23:58
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save treshugart/aebe9c8f5f3848726d20986c45f1f64d to your computer and use it in GitHub Desktop.
Save treshugart/aebe9c8f5f3848726d20986c45f1f64d to your computer and use it in GitHub Desktop.
A React renderer for SkateJS. In action: https://www.webpackbin.com/bins/-KsfBg-KmRwisjp9ff80.
import React, { Component } from 'react';
import { render } from 'react-dom';
import { props, withProps } from 'skatejs/esnext/with-props';
import { withRender } from 'skatejs/esnext/with-render';
// This is the React renderer mixin.
const withReact = Base => class extends withRender(withProps(Base || HTMLElement)) {
get props () {
// We override props so that we can satisfy most use
// cases for children by using a slot.
return {
...super.props,
...{ children: <slot /> }
};
}
rendererCallback (renderRoot, renderCallback) {
render(renderCallback(), renderRoot);
}
}
// For convenience and so we don't have to re-extend everytime.
const ReactComponent = withReact();
// React component we want to wrap in the web component.
class ReactHello extends Component {
render() {
const { children, yell } = this.props;
return (
<div>Hello, {yell ? <strong>{children}</strong> : children}!</div>
);
}
}
// Web component that renders using React. This is all you need
// to do to wrap the React component. All props can be passed
// down and {children} becomes <slot />.
class WcHello extends ReactComponent {
static props = {
// Unfortunately we need to declare props on the custom element
// because it needs to be able to link between observed attributes
// and properties.
//
// You could write a Babel plugin to transform Flow types to
// property definitions, but we haven't done that yet.
yell: props.boolean
}
renderCallback({ props }) {
return (
<ReactHello {...props} />
);
}
}
customElements.define('wc-hello', WcHello);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment