1.0.2 • Published 10 months ago
@beuluis/regis-tag-me v1.0.2
About The Project
Defines react based custom elements and validates the attributes.
Installation
npm i @beuluis/regis-tag-me zodUsage
import {
useWebComponentContext,
registerWebComponent,
} from "@beuluis/regis-tag-me";
import { z } from "zod";
const MyCustomElement = ({
firstName,
showGreeting = true,
}: {
firstName: string;
showGreeting: boolean;
}) => {
const { containerElement, element, hasShadowDom, stylesContainer } =
useWebComponentContext();
return (
<div>
Hello {firstName} from {element.tagName}. I am{" "}
{hasShadowDom ? "" : "not"} rendered in a shadow DOM.
</div>
);
};
registerWebComponent(
"my-custom-element",
MyCustomElement,
z.interface({
firstName: z.string().default("Guest"),
useShadow: z.stringbool({
falsy: ["false"],
truthy: [""], // empty string is truthy since its what we get when the attribute is just set without a value
}),
}),
{
shadowDOM: ({ useShadow }) => useShadow,
},
);Use the custom tag in your HTML:
<html>
<head>
<script src="yourBundle.js"></script>
</head>
<body>
<!-- Result: Hello John from MY-CUSTOM-ELEMENT. I am rendered in a shadow DOM. -->
<my-custom-element first-name="John" use-shadow />
<!-- Result: Hello John from MY-CUSTOM-ELEMENT. I am not rendered in a shadow DOM. -->
<my-custom-element first-name="John" />
</body>
</html>registerWebComponent
Registers a React component as a Web Component (Custom Element) using the given tag name. Takes registerWebComponent as arguments.
useWebComponentContext
Provides a context for the web component. Returns WebComponentContext.
Interfaces
registerWebComponent
tagName- The name of the custom elementComponent- The React component to render inside the web componentattributeSchema- StandardSchemaV1 defining the attributes/props for the componentoptions- Additional configuration optionsmixin- Optional mixin to extend the web component's functionality. Runs after this library's logicshadowDOM- Controls whether to use Shadow DOM- If boolean: directly determines Shadow DOM usage
- If function: dynamically determines Shadow DOM usage based on attributes. This only takes effect on the first render
WebComponentContext
containerElement- The element to mount the web component inelement- The web component elementhasShadowDom- Whether the web component uses Shadow DOMstylesContainer- The element to mount custom styles in