Build Web Components with React or Preact (without any extra effort)
MIT License
Build and export React Components as Web Components without any extra effort.
Size = ~1.5kB after gzip
* works nicely with preact aswell: See demo
npm install react-webcomponentify
or
yarn add react-webcomponentify
Simple use case
import React from "react";
import { registerAsWebComponent } from "react-webcomponentify";
export const ExampleReactComponent = () => {
return <div> Hello </div>;
};
registerAsWebComponent(ExampleReactComponent, "example-component");
In HTML:
<!DOCTYPE html>
<html>
....
<body>
<example-component />
</body>
....
</html>
You can send serializable string props via the html attributes itself. But for props like callback functions or complex objects you can use the setProps
method on the element as shown below.
import React from "react";
import { registerAsWebComponent } from "react-webcomponentify";
export const ButtonComponent = props => {
return (
<div>
Hello <button onClick={props.onClick}>{props.text}</button>
</div>
);
};
registerAsWebComponent(ButtonComponent, "button-web");
In HTML:
<!DOCTYPE html>
<html>
....
<body>
<button-web text="click me" id="mybutton" />
</body>
....
<script>
const myBtn = document.getElementById("mybutton");
myBtn.setProps({
onClick: () => console.log("btn was clicked")
});
</script>
</html>
Every custom component built using react-webcomponentify will have an instance method setProps
element.setProps({
....
/* set the props here that you want to send to react */
....
})
Thats possible too 😎
import React from "react";
import { registerAsWebComponent } from "react-webcomponentify";
// You access the children just like you would in react (using this.props.children)
export const ComponentWithChild = props => {
return (
<div>
Hello World
{this.props.text}
<div>{this.props.children}</div>
</div>
);
};
registerAsWebComponent(ComponentWithChild, "component-with-child");
In HTML:
<!DOCTYPE html>
<html>
....
<body>
<component-with-child text="I love children">
<p>Some child</p>
</component-with-child>
</body>
....
</html>
This will send <p>Some Child</p>
via this.props.children to the React component ComponentWithChild
.
Note that <p>Some Child</p>
is a dom node and not a react component. So it will be wrapped with a simple react component found here: https://github.com/a7ul/react-webcomponentify/blob/master/src/react-dom-child.js
But for implementation purposed use it like a regular child component.
This library is written in TypeScript. All declarations are included.