Skip to content

Instantly share code, notes, and snippets.

@adarsh0d
Created July 17, 2021 04:45
Show Gist options
  • Save adarsh0d/adce815fcfab43a17a35d200d1affe6e to your computer and use it in GitHub Desktop.
Save adarsh0d/adce815fcfab43a17a35d200d1affe6e to your computer and use it in GitHub Desktop.
Convert react component to web component (antd component to web component)
import { Button } from 'antd';
import * as React from 'react';
import { render, unmountComponentAtNode } from 'react-dom';
import Sample from './Sample';
import Sample2 from './Sample2';
export default function create(ReactComponent, tagName) {
class ReactElement extends HTMLElement {
static observedAttributes = ['value'];
connectedCallback() {
this._innerHTML = this.innerHTML;
this.mount();
}
disconnectedCallback() {
this.unmount();
this.observer.disconnect();
}
attributeChangedCallback() {
this.unmount();
this.mount();
}
mount() {
const props = {
...this.getProps(this.attributes),
...this.getEvents(),
children: this.innerHTML
};
render(<ReactComponent {...props} />, this);
}
unmount() {
unmountComponentAtNode(this);
}
getProps(attributes) {
return [...attributes]
.filter(attr => attr.name !== 'style')
.map(attr => this.convert(attr.name, attr.value))
.reduce((props, prop) =>
({ ...props, [prop.name]: prop.value }), {});
}
getEvents() {
return Object.values(this.attributes)
.filter(key => /on([a-z].*)/.exec(key.name))
.reduce((events, ev) => ({
...events,
[ev.name]: args =>
this.dispatchEvent(new CustomEvent(ev.name, { ...args }))
}), {});
}
convert(attrName, attrValue) {
let value = attrValue;
if (attrValue === 'true' || attrValue === 'false')
value = attrValue === 'true';
else if (!isNaN(attrValue) && attrValue !== '')
value = +attrValue;
else if (/^{.*}/.exec(attrValue))
value = JSON.parse(attrValue);
return {
name: attrName,
value: value
};
}
}
customElements.define(tagName, ReactElement);
}
create(Sample, 'rating-element')
create(Sample2, 'btn-element')
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="theme-color" content="#000000" />
<meta
name="description"
content="Web site created using create-react-app"
/>
<link rel="apple-touch-icon" href="%PUBLIC_URL%/logo192.png" />
<!--
manifest.json provides metadata used when your web app is installed on a
user's mobile device or desktop. See https://developers.google.com/web/fundamentals/web-app-manifest/
-->
<link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
<!--
Notice the use of %PUBLIC_URL% in the tags above.
It will be replaced with the URL of the `public` folder during the build.
Only files inside the `public` folder can be referenced from the HTML.
Unlike "/favicon.ico" or "favicon.ico", "%PUBLIC_URL%/favicon.ico" will
work correctly both with client-side routing and a non-root public URL.
Learn how to configure a non-root public URL by running `npm run build`.
-->
<title>React App</title>
</head>
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root"></div>
<rating-element id="5" onbuttonpress="onbuttonpress"></rating-element>
<btn-element type="primary" id="5" onbuttonpress="onbuttonpress">Click Me</btn-element>
<div id="result"></div>
<!--
This HTML file is a template.
If you open it directly in the browser, you will see an empty page.
You can add webfonts, meta tags, or analytics to this file.
The build step will place the bundled scripts into the <body> tag.
To begin the development, run `npm start` or `yarn start`.
To create a production bundle, use `npm run build` or `yarn build`.
-->
<script>
const reactEl = document.getElementsByTagName('rating-element')[0];
var reactResultEl = document.getElementById('result');
reactEl.addEventListener("onbuttonpress", function (e) {
console.log(e.detail)
reactResultEl.innerHTML = "You have rated "
});
var btnEl = document.getElementsByTagName('btn-element')[0];
btnEl.addEventListener("onbuttonpress", function (e) {
reactResultEl.innerHTML = "You have rated "
});
</script>
</body>
</html>
import React from 'react'
import PropTypes from 'prop-types';
import { Button, DatePicker } from 'antd';
const Sample = (props) => {
console.log(props)
const { onbuttonpress, ...remainingProps } = props
return (
<DatePicker {...remainingProps} onChange={(date, dateString) => onbuttonpress({ detail: {date, dateString} })} />
)
}
export default Sample
import React from 'react'
import PropTypes from 'prop-types';
import { Button, DatePicker } from 'antd';
const Sample2 = (props) => {
console.log(props)
const { onbuttonpress, ...remainingProps } = props
return (
<Button {...remainingProps} onClick={onbuttonpress} />
)
}
export default Sample2
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment