Project Status
Use case
Write web components with little code or turn existing React components into web components. Attributes are converted into typed properties, callbacks of the component become DOM events and templates are re-rendered when properties change. The resulting custom elements work in plain HTML and in any framework.
Content
Installation
npm install web-component-wrapper clientnode core-js
Wrapping React components additionally needs "react" and "react-dom". The bundle "web-component-wrapper/bundle" already contains all dependencies, including React, and can also be loaded from a CDN like "https://unpkg.com/web-component-wrapper@latest/dist/bundle/index.js". For older browsers use the "compatible" variants.
Own web components
Derive from "Web", set "doRender" and describe the markup in "content". Expressions in "${...}" see all properties and are evaluated again whenever a property changes. "property" declares a property, its attribute is the name in kebab case:
import {string} from 'clientnode/property-types'
import {property, Web} from 'web-component-wrapper'
class MyGreeting extends Web {
static doRender = true
// NOTE: No template literal, "${...}" is evaluated when rendering.
static content =
'<button bind-on-click="self.greetingName = \'you\'">' +
'Hello ${greetingName}!' +
'</button>'
}
property({type: string})(MyGreeting.prototype, 'greetingName')
customElements.define('my-greeting', MyGreeting)
<my-greeting greeting-name="World"></my-greeting>
Values are inserted as HTML, so do not render untrusted input this way. With TypeScript you can use "@property" as decorator on class fields. Then call "this.defineGetterAndSetterInterface()" in the constructor, since class field initialization would otherwise overwrite the generated accessors.
Wrapping React components
"wrapAsWebComponent" turns a React component into a web component. Its "propTypes" define the properties. Callbacks like "onChange" are dispatched as DOM events ("change"):
import {func, number, string} from 'clientnode/property-types'
import {createElement} from 'react'
import {wrapAsWebComponent} from 'web-component-wrapper'
const Counter = ({count = 0, label = 'Clicks', onChange}) =>
createElement(
'button',
{onClick: () => onChange?.({count: count + 1})},
`${label}: ${count}`
)
Counter.propTypes = {count: number, label: string, onChange: func}
wrapAsWebComponent(
Counter,
'Counter',
{
controllableProperties: ['count'],
propertiesToReflectAsAttributes: {count: number}
}
).register('my-counter')
<my-counter count="2" label="Votes"></my-counter>
<script>
document.querySelector('my-counter').addEventListener(
'change', (event) => console.log(event.detail.parameters[0].count)
)
</script>
An object passed to a callback updates the matching properties. "controllableProperties" lists those the web component manages itself, so the button counts up without any surrounding code. "propertiesToReflectAsAttributes" writes them back as attributes. Further options:
- "eventToPropertyMapping": Maps callback arguments to properties per event, e.g. {onChange: (value) => ({value})}.
- "propertyAliases": Alternative property names.
- "internalProperties": Fixed properties passed to the React component.
- "propTypes": Property types if the component does not define them.
"register" without argument derives the tag name from the component name, e.g. "TextInput" becomes "text-input". Since tag names need a hyphen, single words get the prefix "web-", e.g. "Counter" becomes "web-counter".
Attributes and properties
The type of a property decides how its attribute is read:
- "string": Taken as it is.
- "boolean": Set by the presence of the attribute.
- "func": The attribute value is a function body. "event" and "parameters" hold the arguments of a call.
- All other types, like "number", "object" or "array": Evaluated as JavaScript expression.
For a component with the properties "title" (string), "highlighted" (boolean), "options" (object) and "onSelect" (func):
<my-card
highlighted
on-select="console.log('Selected', parameters)"
options="{size: 2 * 21}"
title="Welcome"
></my-card>
Setting a property via JavaScript ("element.title = 'New'") renders again as well.
Bindings in templates
Elements inside "content" can bind to the component, and so can the component's own element in HTML. Expressions see the properties, "self" (the component), "parentInstance", "rootInstance" and for events "event" and "parameters":
- "bind-on-<event>": Runs code on an event, e.g. "bind-on-click".
- "bind-attribute-<name>": Sets an attribute to the expression's value.
- "bind-property-<name>": Sets a DOM property to the expression's value.
<my-counter
bind-on-change="console.log(event.detail.parameters[0].count)"
></my-counter>
Each of them can also be written with a "data-" prefix to keep the markup valid HTML.
Development
yarn install
yarn start
yarn test
"yarn start" serves a playground with examples.
About this website
Provider ofhttps://tsickert.com/web-component-wrapper:
Torben Sickert
Waldstraße 29
79194 Gundelfingen i.Br.
Phone: +49 (0) 176 / 10 248 185
Email: [email protected]
Website: https://tsickert.com
Disclaimer
Liability for content
The content of our pages has been prepared with the utmost care. However, we cannot guarantee the accuracy, completeness or timeliness of the content. As a service provider, we are responsible for our own content on these pages under general law. However, we are not obliged to monitor transmitted or stored third-party information or investigate circumstances that indicate illegal activity. Obligations to remove or block the use of information under general law remain unaffected. Liability in this respect is only possible from the time we become aware of a specific infringement. Upon becoming aware of any such legal violations, we will remove this content immediately.
Liability for links
Our website contains links to external third-party websites whose content is beyond our control. We therefore cannot accept any responsibility for such third-party content. The respective provider or operator of each linked site is always responsible for its content. The linked sites were checked for possible legal violations when the links were created. No illegal content was apparent at that time. However, continuous monitoring of linked sites is not reasonable without specific evidence of a legal violation. If we become aware of any legal violations, we will remove the relevant links immediately.
Copyright
Content and works on these pages created by the site operators are subject to German copyright law. Reproduction, adaptation, distribution and any use beyond the scope of copyright law require the written consent of the respective author or creator. Downloads and copies of this site are permitted for private, non-commercial use only. Where content on this site was not created by the operator, third-party copyrights are respected. In particular, third-party content is identified as such. If you become aware of a copyright infringement, please notify us. Upon becoming aware of any legal violations, we will remove the relevant content immediately.
Privacy Policy
You can generally use our website without providing personal data. Where personal data (such as names, addresses or email addresses) is collected on our pages, this is, wherever possible, always done on a voluntary basis. This data will not be passed on to third parties without your express consent. Please note that data transmission over the internet (for example, when communicating by email) may have security vulnerabilities. It is not possible to completely protect data against access by third parties. We expressly object to the use by third parties of contact details published to meet legal notice requirements for sending unsolicited advertising or information. The site operators expressly reserve the right to take legal action if unsolicited advertising, such as spam emails, is sent.
Content Delivery Network (Cloudflare)
We use Cloudflare (Cloudflare, Inc., 101 Townsend St., San Francisco, CA 94107, USA) to protect and speed up our website. This constitutes a legitimate interest within the meaning of Art. 6(1)(f) GDPR. Cloudflare processes log data (including IP addresses) and sets technically necessary cookies to defend against malicious bot traffic. We have concluded a Data Processing Addendum (DPA) with Cloudflare based on the EU Standard Contractual Clauses. Cloudflare is certified under the EU-U.S. Data Privacy Framework.
Privacy Statement for a possible use of Google Analytics
This website may use Google Analytics 4, a web analytics service provided by Google Ireland Limited ("Google", Gordon House, Barrow Street, Dublin 4, Ireland). If it is used, data is processed solely on the basis of your express consent (Art. 6(1)(a) GDPR). Google Analytics uses cookies that enable analysis of how you use the website. Information generated by these cookies about your use of this website is transmitted to and stored on a Google server; transfer of data to third countries (such as the United States) cannot be ruled out. IP anonymization is enabled by default on this website, so Google truncates your IP address within a member state of the European Union or another state party to the Agreement on the European Economic Area before transmission. You may withdraw your consent at any time with effect for the future through the cookie settings (our consent tool), or prevent data collection by using the official Google browser add-on.
Copyright Statement
Unless noted otherwise, all artwork on this website is protected property of the website author. Any use for commercial purpose, reproduction and publication requires the author's written permission. Commercial work created in cooperation or bound by contract with third parties are specifically marked. Respective copyrights apply.