@beuluis/regis-tag-me
v2.0.0
Published
Defines react based custom elements and validates the attributes
Maintainers
Readme
About The Project
Defines react based custom elements and validates the attributes.
Installation
npm i @beuluis/regis-tag-me zodUsage
import {
attributeBoolean,
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: attributeBoolean,
}),
{
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.
attributeBoolean
Booleans based on attributes can be tricky.
To help with this this library exports attributeBoolean which is a pre-configured schema that parses attribute based booleans correctly.
Example:
<!-- Result: true -->
<my-custom-element this-is-a-bool />
<!-- Result: true -->
<my-custom-element this-is-a-bool="true" />
<!-- Result: false -->
<my-custom-element this-is-a-bool="false" />
<!-- Result: false -->
<my-custom-element />If this parsing is not wanted or desired you can checkout Zod´s stringbool
Interfaces
registerWebComponent
tagName- The name of the custom elementComponent- The React component to render inside the web componentattributeSchema- Zod 4 or Zod 4-mini object schema 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
