Skip to content

Preact

TypeScript Configuration

Add the Web Component types to your TypeScript configuration:

tsconfig.json
{
"compilerOptions": {
"types": [
// Required: Enables JSX type support for Preact
// Or a single component: "@staticview/ui/types/preact/[component-name]"
"@staticview/ui/types/preact",
// Optional: Adds native DOM types (e.g. `querySelector`, `document`)
// Or a single component: "@staticview/ui/types/dom/[component-name]"
"@staticview/ui/types/dom",
// Optional: Exposes component types globally (no imports needed)
// Or a single component: "@staticview/ui/types/global/[component-name]"
"@staticview/ui/types/global",
],
},
}

This provides TypeScript support for the web components in your Preact application.

Importing Web Components

Web components are registered globally in the browser. Import them once in your application's entry point:

app.tsx
import "@staticview/ui/[component-name]";

Important: Do not import web components in multiple files. Import them only once at application startup.

Setting Properties and Attributes

If the web component has a JavaScript property, Preact will automatically set it, otherwise, it sets it as an HTML attribute.

<component-name opened={isOpen} label="Title"></component-name>

Boolean Attributes

A boolean attribute is on whenever it is present, whatever its value: close-button="false" turns the close button on. Preact removes an attribute whose value is false, so pass a boolean and let Preact add or remove it:

<component-name close-button={hasCloseButton}></component-name>

Prefer the matching JavaScript property when the component has one. Preact assigns it directly on the element, so the value reaches the component as a boolean instead of as markup. The component decides whether to reflect it back to the attribute:

<component-name closeButton={hasCloseButton}></component-name>

Handling Events

Use on[eventName] syntax to listen for custom events:

<component-name onopened={handleOpen}></component-name>

Controlled and Uncontrolled Components

On every render, Preact sets value and checked again on any element whose current value differs from the prop, web components included. A component that gets value without the state following the user's change resets on the next render, even an unrelated one.

For an uncontrolled component, set the starting value with defaultValue or defaultChecked instead. A form reset returns to it:

<component-name defaultValue="first"></component-name>

For a controlled component, pass the state and cancel the event that the component fires before a user change applies. Then update the state yourself:

<component-name
value={value}
onclicked={event => {
event.preventDefault();
setValue(event.detail.value);
}}
></component-name>

Using Slots

Use children to render the content of the web component:

<component-name>
<span slot="title">Title</span>
<span>Content</span>
</component-name>