1.0.2 • Published 10 months ago

@beuluis/regis-tag-me v1.0.2

Weekly downloads
-
License
MIT
Repository
github
Last release
10 months ago

Contributors Forks Stargazers Issues

About The Project

Defines react based custom elements and validates the attributes.

Installation

npm i @beuluis/regis-tag-me zod

Usage

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 element
  • Component - The React component to render inside the web component
  • attributeSchema - StandardSchemaV1 defining the attributes/props for the component
  • options - Additional configuration options
    • mixin - Optional mixin to extend the web component's functionality. Runs after this library's logic
    • shadowDOM - 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 in
  • element - The web component element
  • hasShadowDom - Whether the web component uses Shadow DOM
  • stylesContainer - The element to mount custom styles in