Skip to content

Instantly share code, notes, and snippets.

@blasten
Last active March 24, 2017 17:18
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save blasten/07a3687cb24464b5350632dbc935d777 to your computer and use it in GitHub Desktop.
Save blasten/07a3687cb24464b5350632dbc935d777 to your computer and use it in GitHub Desktop.
custom elements in Preact or React without CE polyfills.
const HAS_NATIVE_CE = window.customElements != null;
const HTMLElement = HAS_NATIVE_CE ? window.HTMLElement : class{ constructor(self) { return self; } };
export class CustomElement extends HTMLElement {
constructor(inst) {
this.__instance = super(inst);
return this.__instance;
}
get props() {
return Object.assign({}, this.__props);
}
set props(props) {
this.__props = props;
// debounce __render(props, oldProps); if props !== oldProps
}
connectedCallback() {
console.log('connected');
}
static setProps(props) {
return (ref) => {
if (!ref.__instance) {
ref.__instance = new CustomElement(ref);
ref.__instance.connectedCallback();
}
ref.__instance.props = props;
};
}
}
if (HAS_NATIVE_CE) {
customElements.define('custom-element', CustomElement);
}
import CustomElement from './CustomElement';
export default class PreactComponent extends Component {
render({ prop1, prop2 } = props) {
return (
<custom-element
ref={
CustomElement.setProps(
{
prop1: prop1,
prop2: prop2
}
);
}
/>
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment