Web Components with react
·
Report Bug
·
Request Feature
·
Defines react based custom elements and validates the attributes.
npm i -D @beuluis/regis-tag-me
import {
useWebComponentContext,
registerWebComponent,
} from "@beuluis/regis-tag-me";
import { z } from "zod";
const MyCustomElement = ({ firstName }: { firstName: string }) => {
const { containerElement, element, hasShadowDom, stylesContainer } =
useWebComponentContext();
return (
<div>
Hello {firstName} from {element.tagName}
</div>
);
};
registerWebComponent(
"my-custom-element",
MyCustomElement,
z.object({
firstName: z.string().default("Guest"),
}),
);
Use the custom tag in your HTML:
<!-- Result: Hello John from MY-CUSTOM-ELEMENT -->
<my-custom-element first-name="John" />
Registers a React component as a Web Component (Custom Element) using the given tag name. Takes registerWebComponent as arguments.
Provides a context for the web component. Returns WebComponentContext.
tagName
- The name of the custom elementComponent
- The React component to render inside the web componentattributeSchema
- Zod schema defining the attributes/props for the component with automatic type conversion for primitives (string, number, boolean, etc.)options
- Additional configuration optionsmixin
- Optional mixin to extend the web component's functionalityshadowDOM
- Controls whether to use Shadow DOM- If boolean: directly determines Shadow DOM usage
- If function: dynamically determines Shadow DOM usage based on attributes
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