Preact
Preact
Unfortunately, integrating native web components in modern Javascript Frameworks like Preact can be tricky sometimes.
To make working with Cosmos web components more convenient and practical, we provide a Preact wrapper library in the @cosmos/web-preact package.
Use web components as first-class Preact components
The Preact wrapper hides all the quirks when working with web components and makes integrating Cosmos feel as native as working with Preact components.
Typescript support for properties, events, and methods
All Cosmos Preact web components are strongly typed to support using them the right way.
Fixes Server-Side Rendering with Preact
Preact's way of working and integrating web components is breaking server-side pre-rendered web components. Cosmos' Preact wrapper fixes this issue for you by always defining all critical properties on a component.
Auto-definition of required web components
The wrapping component takes care of registering and defining the required web components in the background the moment you are using the component.
⚠️ Deprecation
With release v9.7.0 the Preact wrapper is provided as standalone package. For projects upgrading from a previous version, the dependencies and imports of the core package @cosmos/web have to be replaced with @cosmos/web-preact. (deprecation roadmap)
"dependencies": {
// "@cosmos/web": "9.6.0",
"@cosmos/web-preact": "9.7.0"
}Usage
import { h, render } from "preact";
import { CosmosButton } from "@cosmos/web-preact";
const app = (
<CosmosButton
kind='tertiary'
size='small'
>
Cosmos Button
</CosmosButton>
);
render(app, window.document.body);Typescript
All Preact components are strongly typed. Additionally, a component's property type is made available as well.
import { h, render } from "preact";
import { CosmosButton } from "@cosmos/web-preact";
import type { CosmosButtonProps } from "@cosmos/web-preact";
const buttonProps : CosmosButtonProps = {
kind: 'tertiary',
size: 'small',
shape: 'rectangle',
appearance: 'dark',
};
const App = () => (
<CosmosButton
{...buttonProps}
>
Cosmos Button
</CosmosButton>
);
render(<App />, window.document.body);Reference the Custom Element
Sometimes a reference to the underlying rendered custom element is required in order to call public methods or utilize the Javascript DOM API.
import { h, render, createRef } from "preact";
import { CosmosButton } from "@cosmos/web-preact";
import type { CosmosButtonProps, CosmosButtonElement } from "@cosmos/web-preact";
const buttonRef = createRef();
const App = () => (
<CosmosButton
ref={buttonRef}
>
Cosmos Button
</CosmosButton>
);
render(<App />, window.document.body);
const buttonElement : CosmosButtonElement = buttonRef.current.base;