tyom / preact-custom-element

Wrap your component up as a custom element

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

preact-custom-element

CircleCI BrowserStack Status

Generate/register a custom element from a preact component. As of 3.0.0, this library implements the Custom Elements v1 spec. Previous versions (< 3.0.0) implemented the v0 proposal, which was only implemented in Chrome and is abandoned.

Usage

Import CustomElement and call with your component a tag name *, and a list of attribute names you want to observe:

import registerCustomElement from "preact-custom-element";

const Greeting = ({ name = "World" }) => (
	<p>Hello, {name}!</p>
);

registerCustomElement(Greeting, "x-greeting", ["name"]);

* Note: as per the Custom Elements specification, the tag name must contain a hyphen.

Use the new tag name in HTML, attribute keys and values will be passed in as props:

<x-greeting name="Billy Jo"></x-greeting>

Output:

<p>Hello, Billy Jo!</p>

Why the prop names parameter?

The Custom Elements V1 spec requires you to explictly state the attribute names you want to observe. From your Preact component perspective, props could be an object with any keys at runtime. This unfortunate combination of factors leaves us needing to explicitly state them.

It's possible that a compile step could introspect your usages of props and generate the glue code here. Please send me a link if you do this!

Related

preact-shadow-dom

Thanks

Big thanks to BrowserStack for providing service for CI on this project! BrowserStack allows us to test this project on all real browsers that support Custom Elements, including mobile browsers.

About

Wrap your component up as a custom element

License:MIT License


Languages

Language:JavaScript 100.0%