Skip to content

Preact

Use staticview components in Preact JSX.

TypeScript Configuration

Add the component types to your TypeScript configuration:

tsconfig.json
{
"compilerOptions": {
"types": [
// Required: types the component tags in Preact JSX
// For one component: "@staticview/ui/types/preact/[component-name]"
"@staticview/ui/types/preact",
// Optional: types what `querySelector` and `createElement` return for each tag
// For one component: "@staticview/ui/types/dom/[component-name]"
"@staticview/ui/types/dom",
// Optional: declares each component type globally, with no import
// For one component: "@staticview/ui/types/global/[component-name]"
"@staticview/ui/types/global",
],
},
}

Importing Web Components

Since components register globally, import each one once, in your app's entry point:

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

Setting Properties and Attributes

Preact sets a prop as a property when the element has one, and as an attribute otherwise:

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

Boolean Attributes

A boolean attribute is on whenever it is present, and close-button="false" turns the close button on. Pass a boolean, and Preact adds the attribute for true and removes it for false:

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

When the component has a matching property, prefer it, since Preact assigns it on the element as a boolean:

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

Handling Events

Listen to component events with on[eventName]:

<component-name onopenedchange={handleOpenedChange}></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 while the state does not follow 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, which a form reset also returns to:

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

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

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

Using Slots

Pass the content as children, with a slot attribute for a named slot:

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