@merzin/element
v0.3.0
Published
This package exports two (2) primary functions:
Readme
Element
This package exports two (2) primary functions:
createElement: extendeddocument.createElementwhich can be used as a JSX factory. It has an aliashwhich is also exported. Can also be imported from "@merzin/element/createElement".tag: class decorator function for declaring the tag name of a web component. Can also be imported from "@merzin/element/tag".
When importing package root — "@merzin/element", functions tag and
createElement (also it's alias h) are injected into globalThis which means
they can be used without explicitly importing them in the current file and in
all subsequently imported files.
Decorator tag
Class decorator tag can be used to define a custom element. Note that tag name
must include a hyphen.
import { tag } from "@merzin/element/tag";
@tag("my-component")
class MyComponent extends HTMLElement {}
document.createElement("my-component");Function createElement
Function createElement (and it's alias h) is an extended version of
document.createElement. createElement can be used to create HTML elements
with a tag name, the same as document.createElement.
But createElement optionally accepts one or more additional arguments. The
second parameter is a properties object of values to be assigned to the element
after creation. Rest of the arguments are treated as content and are appended
to the element. Content arguments can be of type string, HTMLElement,
false, null, undefined or an array of them (falsy values are ignored).
The first argument can also be a
Factory<HTMLElement>, i.e. an
HTMLElement or a class extending HTMLElement with no constructor parameters
or a function returning an HTMLElement with no parameters.
Example
import "@merzin/element";
@tag("input-element")
class InputElement extends HTMLElement {
private labelElement: HTMLLabelElement;
private inputElement: HTMLInputElement;
get label(): string {
return this.labelElement.innerText;
}
set label(value: string) {
this.labelElement.innerText = value;
}
get value(): string {
return this.inputElement.value;
}
set value(value: string) {
this.inputElement.value = value;
}
constructor() {
super();
this.replaceChildren(
(this.labelElement = createElement("label", {}, "Initial label")),
(this.inputElement = createElement("input", { type: "text" })),
);
}
}
const input = createElement(InputElement, {
label: "Label",
value: "Value",
});