solid2-wc
v0.0.4
Published
Typed, reactive Web Component adapters for Solid 2
Maintainers
Readme
solid2-wc
Wrap native Web Components as typed, reactive Solid 2 components.
solid2-wc connects a Custom Element to Solid 2 without replacing its DOM node or requiring JSX support for arbitrary custom-element tags. Define the mapping once, then use the result as a normal Solid component. It supports reactive JavaScript properties, string and boolean attributes, case-sensitive custom events, forwarded native DOM props, children/slots, refs, and registration after mounting.
Requirements: Solid 2 (solid-js and @solidjs/web) and autonomous custom elements (tags such as my-counter). Server rendering and hydration are supported when the host resolves Solid's server and browser runtimes for their respective environments. Solid 1 is not supported.
Install
npm install solid2-wcsolid-js and @solidjs/web are peer dependencies, not bundled dependencies. Install compatible Solid 2 versions in your application; this package currently declares ^2.0.0-rc.15 for both.
Configure TSX for Solid 2. For example, with TypeScript use "jsx": "preserve" and "jsxImportSource": "@solidjs/web".
Quick start
The example below assumes a registered <my-counter> custom element exposing a value property and emitting value-change with a numeric detail.value. The adapter does not implement the custom element itself.
/** @jsxImportSource @solidjs/web */
import { createSignal } from "solid-js";
import { webComponent } from "solid2-wc";
interface CounterElement extends HTMLElement {
value: number;
}
interface CounterProps {
value: number;
disabled?: boolean;
label?: string | null;
onValueChange?: (event: CustomEvent<{ value: number }>) => void;
}
const Counter = webComponent<CounterElement, CounterProps>("my-counter", {
properties: ["value"],
booleanAttributes: { disabled: "disabled" },
attributes: { label: "aria-label" },
events: { onValueChange: "value-change" },
});
export function Example() {
const [count, setCount] = createSignal(1);
return (
<>
<button onClick={() => setCount((n) => n + 1)}>Increment</button>
<Counter
value={count()}
disabled={false}
label="Current count"
onValueChange={(event) => setCount(event.detail.value)}
class="counter"
/>
</>
);
}Counter renders an actual <my-counter> node. Updates to count() assign to the element's JavaScript value property (not a string attribute).
Server rendering and hydration
The wrapper renders a custom-element tag and its light-DOM children on the server. Forwarded HTML attributes and mapped string/boolean attributes appear in the HTML. Mapped JavaScript properties, custom event handlers, and refs are attached in the browser when Solid hydrates the existing element. A property waiting for a late custom-element definition receives its latest value after upgrade.
// Use the same component and props in the server render and browser hydrate calls.
const Greeting = webComponent<HTMLElement, { label: string }>("my-greeting", {
attributes: { label: "aria-label" },
});
<Greeting label="Hello"><span slot="message">Welcome</span></Greeting>
// Server HTML includes <my-greeting aria-label="Hello">...</my-greeting>.Custom-element implementations that access HTMLElement, document, or customElements at module load must be imported or defined only in the browser. The component factory itself can run on the server without those globals. Ensure the host application's SSR loader resolves external package imports, including this package's peer dependencies, in its worker or server runtime; a document import map does not resolve imports inside a worker.
API
The package exports one function and two types:
import {
webComponent,
type WebComponentOptions,
type WebComponentProps,
} from "solid2-wc";webComponent<E extends HTMLElement, P extends object = {}>(
tagName: `${string}-${string}`,
options?: WebComponentOptions<P>,
): Component<WebComponentProps<E, P>>;E is the native custom-element instance type used by refs. P is your declared component-props interface, including any custom event handler props. The type parameters make the interface safer at compile time; they do not automatically discover the element's properties or events.
Configuration
| Option | Type | Behavior |
| --- | --- | --- |
| define | CustomElementConstructor | If supplied and not already registered, register the constructor as tagName. Existing definitions are left untouched. |
| properties | readonly (keyof P & string)[] | Read props reactively and assign their values directly to native element properties; object identity is preserved. |
| attributes | Partial<Record<keyof P & string, string>> | Map a prop to a named string-valued DOM attribute. null, undefined, or false removes it. |
| booleanAttributes | Partial<Record<keyof P & string, string>> | Map a prop to the presence/absence of an attribute according to its truthiness. |
| events | Partial<Record<keyof P & string, string>> | Map a callback prop to a native, case-sensitive event type using addEventListener. The latest handler is read when the event fires. |
Every name listed in these options is handled by the adapter and excluded from generic DOM prop forwarding.
Exported types
The public definitions are equivalent to:
import type { Component } from "solid-js";
import type { JSX } from "@solidjs/web/jsx-runtime";
type StringKey<T> = Extract<keyof T, string>;
type CustomElementTag = `${string}-${string}`;
export type WebComponentProps<E extends HTMLElement, P extends object> =
P &
Omit<JSX.HTMLAttributes<E>, keyof P | "ref" | "children"> & {
children?: JSX.Element;
ref?: (element: E) => void;
};
export interface WebComponentOptions<P extends object> {
define?: CustomElementConstructor;
properties?: readonly StringKey<P>[];
attributes?: Partial<Record<StringKey<P>, string>>;
booleanAttributes?: Partial<Record<StringKey<P>, string>>;
events?: Partial<Record<StringKey<P>, string>>;
}StringKey and CustomElementTag are internal helper types, not separate public exports. The returned component accepts the specified P props plus normal Solid web/DOM attributes (excluding colliding keys), optional children, and a native-element callback ref.
Usage patterns
Preserve object-valued properties
Map objects to properties, not attributes. Properties retain the original JavaScript value and can call a custom element's setter:
interface ChartElement extends HTMLElement {
config: { theme: string; series: number[] };
}
interface ChartProps {
config: ChartElement["config"];
}
const Chart = webComponent<ChartElement, ChartProps>("my-chart", {
properties: ["config"],
});
<Chart config={{ theme: "light", series: [3, 5, 8] }} />Solid must observe a change to reassign a property. Mutating an existing object in place without reactive invalidation does not automatically notify the custom element.
String and boolean attributes
interface DisclosureProps {
titleText?: string | null;
open?: boolean;
}
const Disclosure = webComponent<HTMLElement, DisclosureProps>("my-disclosure", {
attributes: { titleText: "data-title" },
booleanAttributes: { open: "open" },
});
<Disclosure titleText="Details" open={true} />String-attribute values are converted with String(value) unless removed; boolean attributes use native presence/absence, not the strings "true"/"false".
Exact custom event names and casing
Browser DOM event names are case-sensitive. The mapping's value is the exact native event type; no camelCase/kebab-case conversion is performed:
interface GreetingProps {
onGreet?: (event: CustomEvent<string>) => void;
onCapitalGreet?: (event: CustomEvent<string>) => void;
onOddGreet?: (event: CustomEvent<string>) => void;
onGreetAndMeet?: (event: CustomEvent<string>) => void;
onHybridGreetAndMeet?: (event: CustomEvent<string>) => void;
}
const Greeting = webComponent<HTMLElement, GreetingProps>("my-greeting", {
events: {
onGreet: "greet",
onCapitalGreet: "Greet",
onOddGreet: "GreeT",
onGreetAndMeet: "greet-and-meet",
onHybridGreetAndMeet: "greetAnd-Meet",
},
});
<Greeting onGreet={(event) => console.log(event.type, event.detail)} />The underlying custom element can emit new CustomEvent("greet", { detail: "hello" }). In particular, greet is not the same event as Greet or GreeT. Multiple mapped events are listened to independently; listeners are removed when the Solid component is disposed.
Slotted children and native ref
interface PanelElement extends HTMLElement {
open(): void;
}
const Panel = webComponent<PanelElement>("my-panel");
let panel: PanelElement | undefined;
<Panel ref={(element) => { panel = element; }} class="card">
<span slot="header">Settings</span>
<p>Content in the default slot</p>
</Panel>The adapter retains light-DOM children, so the custom element can project them using its own <slot> elements. ref receives the actual HTMLElement instance, not a Solid component facade. The ref callback is a one-time notification; avoid writing Solid reactive state synchronously from it in forbidden Solid 2 owned scopes.
Register before or after mounting
// Creating the wrapper does not require the custom element to be defined.
const Later = webComponent<HTMLElement, { message: string }>("my-later", {
properties: ["message"],
});
// It can be mounted while "my-later" is not yet registered.
// Registration may happen afterward in the browser:
if (typeof customElements !== "undefined") {
customElements.define("my-later", class extends HTMLElement {
set message(value: string) { this.textContent = value; }
});
}The browser upgrades existing <my-later> nodes in place. The adapter defers mapped property assignments until the native definition becomes available, avoiding accidental own-properties that could shadow custom-element setters. Pending writes use the latest value. Attributes and event listeners can already be attached before registration. Unmapped DOM props do not receive this late-upgrade protection.
Alternatively, pass define: MyElementClass to register a constructor if needed. Existing registrations are not overwritten.
Package behavior and constraints
- Autonomous custom elements only: customized built-in elements are not supported.
- Solid 2 only: use the Solid 2 JSX setup and compatible core/web/signals runtime versions.
- Shared reactive runtime: host and adapter must resolve the same Solid runtime. In CDN-powered or esm.sh playgrounds, externalize/share
solid-js,@solidjs/web, and underlying@solidjs/signalsrather than loading separate copies; duplicate runtime instances can causeSTRICT_READ_UNTRACKEDdiagnostics and broken tracking. - Explicit mappings: custom event names and mapped property/attribute names are never inferred; unmapped props follow Solid's ordinary DOM forwarding behavior.
- Lifecycle: native event listeners are cleaned up on Solid disposal; reactive updates are owned by the Solid component. During hydration the existing server-rendered node is reused.
Development
The source repository (not required for npm consumers) includes internal docs/, a root-level playground, and a native Playwright integration suite:
npm install
npx playwright install chromium
npm run dev # local demo
npm test # Playwright integration tests
npm run typecheck
npm run check # typecheck, tests, package verification
npm pack # build and create npm tarballThe npm tarball includes dist/, this README, the license, and package metadata. Tests, playground, internal documentation, and tooling stay in the source repository.
MIT licensed. See LICENSE.
