Wrapper for Web Components so that React will play nice
The wrapper makes for a smooth transition between React and Web Components by allowing to pass objects as attributes, and listen to custom events. Simple attributes (strings, numbers, booleans) are passed in on creation, while complex attributes (objects, arrays) are passed in when the element is mounted.
The custom events are generated by convention. if you add: onEvent={onEvent}
, "on" is removed, and the
remainder is lower-cased. In this case it will look for a event
event:
element.addEventListener('event', callback);
Events with hyphens are now supported:
<Component
onCustomEvent={() => { console.log('custom event'); }}
/>
Same as:
element.addEventListener('custom-event', callback);
export default function Chart ({ title, total, data }) {
function onCustomEvent (e) {
console.log('onCustomEvent', e);
}
return (
<WebComponent
component="chart-pie"
header={title}
total={total}
data={data}
onCustomEvent={onCustomEvent}
>
<div>child</div>
</WebComponent>
);
}
A WebComponent can be updated like any other React Component. Under the hood, shouldComponentUpdate
always returns
false (The JSX is never re-rendered), and instead, the web component's properties are passed in.
If deep
is passed as a prop, shouldComponentUpdate
will do a deep comparison. It defaulst to shallow.
WebComponent has a value
getter, which can come in handy if you need to uses refs
.
In spite of their similarity, properties and attributes ae not the same. It is important that your web component uses
best practices and syncs them, so that element.foo = true
works the same way as element.setAttribute('foo', true);
.
Obviously, you can't set an object via attributes (it coerces into a string). In these cases, they are always passed in as properties.
If desired, pass in an onUnmount
callback which will be fired on componentWillUnmount
, passing the custom element.
As always, free as in beer.