# preact-custom-element 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 Any Preact component can be registered as a custom element simply by importing `register` and calling it with your component, a tag name*, and a list of attribute names you want to observe: ```javascript import register from 'preact-custom-element'; const Greeting = ({ name = 'World' }) =>
Hello, {name}!
; register(Greeting, 'x-greeting', ['name'], { shadow: true, mode: 'open', adoptedStyleSheets: [], serializable: true }); // ^ ^ ^ ^ ^ ^ ^ // | HTML tag name | use shadow-dom | use adoptedStyleSheets | // Component definition Observed attributes Encapsulation mode for the shadow DOM tree Root is serializable ``` > _**Note:** as per the [Custom Elements specification](https://html.spec.whatwg.org/multipage/custom-elements.html#valid-custom-element-name), the tag name must contain a hyphen._ Use the new tag name in HTML, attribute keys and values will be passed in as props: ```htmlHello, Billy Jo!
``` ### Observed Attributes The Custom Elements v1 specification requires explicitly listing the names of attributes you want to observe in order to respond when their values are changed. These can be specified via the third parameter that's passed to the `register()` function: ```js // Listen to changes to the `name` attribute register(Greeting, 'x-greeting', ['name']); ``` If you omit the third parameter to `register()`, the list of attributes to observe can be specified using a static `observedAttributes` property on your Component. This also works for the Custom Element's name, which can be specified using a `tagName` static property: ```js import register from 'preact-custom-element'; //Hello, {name}!
; } } register(Greeting); ``` If no `observedAttributes` are specified, they will be inferred from the keys of `propTypes` if present on the Component: ```js // Other option: use PropTypes: function FullName({ first, last }) { return ( {first} {last} ); } FullName.propTypes = { first: Object, // you can use PropTypes, or this last: Object, // trick to define untyped props. }; register(FullName, 'full-name'); ``` ### Passing slots as props The `register()` function also accepts an optional fourth parameter, an options bag. At present, it allows you to opt-in to using shadow DOM for your custom element by setting the `shadow` property to `true`, and if so, you can also specify the encapsulation mode with `mode`, which can be either `'open'` or `'closed'`. Additionally, you may mark the shadow root as being serializable with the boolean `serializable` property. When using shadow DOM, you can make use of named `{content}