React Web Component
Wrapper for Web Components so that React will play nice
Description
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: onCustomEvent={onCustomEvent}
, "on" is removed, and the
remainder is lower-cased. In this case it will look for a customevent
event:
element.addEventListener('customevent', callback);
Note that events with hyphens are currently not supported.
Example
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>
);
}
State/Props
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.
Note that shouldComponentUpdate
uses a naive comparison (JSON.stringify
) to determine whether to update the property.
This may cause problems if you are passing in extra data that is not valid, such as the window object, or DOM nodes.
The comparison may be updated in the future.
Value
WebComponent has a value
getter, which can come in handy if you need to uses refs
.
Properties/Attributes
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.
onUnmount
If desired, pass in an onUnmount
callback which will be fired on componentWillUnmount
, passing the custom element.
License
As always, free as in beer.