### Install reactement
Source: https://github.com/jahilldev/component-elements/blob/main/packages/reactement/README.md
Installation commands for Yarn and NPM.
```bash
$ yarn add reactement
```
```bash
$ npm i reactement
```
--------------------------------
### Installation
Source: https://github.com/jahilldev/component-elements/blob/main/packages/preactement/README.md
Install preactement using Yarn or NPM.
```APIDOC
## Installation
Install with Yarn:
```bash
$ yarn add preactement
```
Install with NPM:
```bash
$ npm i preactement
```
```
--------------------------------
### ES5 Browser Support Setup
Source: https://github.com/jahilldev/component-elements/blob/main/packages/preactement/README.md
Import polyfills for ES5 compatibility, especially for older browsers like IE11. Ensure '@webcomponents/custom-elements' is installed.
```javascript
import '@webcomponents/custom-elements';
import '@webcomponents/custom-elements/src/native-shim';
```
--------------------------------
### Install Component Elements
Source: https://context7.com/jahilldev/component-elements/llms.txt
Install the required package for either React or Preact.
```bash
# For React
yarn add reactement
# or
npm i reactement
# For Preact
yarn add preactement
# or
npm i preactement
```
--------------------------------
### Install Preactement with NPM
Source: https://github.com/jahilldev/component-elements/blob/main/packages/preactement/README.md
Use this command to add preactement to your project dependencies using NPM.
```bash
$ npm i preactement
```
--------------------------------
### Install Preactement with Yarn
Source: https://github.com/jahilldev/component-elements/blob/main/packages/preactement/README.md
Use this command to add preactement to your project dependencies using Yarn.
```bash
$ yarn add preactement
```
--------------------------------
### Invalid HTML examples
Source: https://github.com/jahilldev/component-elements/blob/main/packages/reactement/README.md
Examples of invalid HTML structures that may cause rendering errors.
```jsx
Hello
Hello
```
--------------------------------
### Custom Element with a Defined Attribute
Source: https://github.com/jahilldev/component-elements/blob/main/packages/preactement/README.md
Example of a custom element utilizing a custom attribute defined in the 'define' options.
```html
```
--------------------------------
### Implement Server-Side Rendering
Source: https://context7.com/jahilldev/component-elements/llms.txt
Demonstrates using define() on the server to return a functional component wrapper that serializes props for client-side hydration.
```tsx
import { define } from 'reactement';
import { renderToString } from 'react-dom/server';
interface ProductCardProps {
name: string;
price: number;
imageUrl: string;
}
function ProductCard({ name, price, imageUrl }: ProductCardProps) {
return (
{name}
${price.toFixed(2)}
);
}
// On server, define() returns a component wrapper
const ProductCardElement = define('product-card', () => ProductCard);
// Use in your server-rendered page
function ProductPage() {
return (
Featured Products
);
}
// Rendered HTML includes props as JSON for client hydration:
//
//
// ...
//
```
--------------------------------
### Using define() - Server (SSR)
Source: https://github.com/jahilldev/component-elements/blob/main/packages/preactement/README.md
Use `define()` to generate a custom element container for server-side rendering.
```APIDOC
## Using define() - On the server (SSR)
You can also use `define()` to generate a custom element container if you're rendering your page in Node. When wrapping your component, e.g:
```ts
define('hero-banner', () => HeroBanner);
```
A functional component is returned that you can include elsewhere in your app. For example:
```tsx
import { define } from 'preactement';
/*[...]*/
const Component = define('hero-banner', () => HeroBanner);
/*[...]*/
function HomePage() {
return (
);
}
```
```
--------------------------------
### Using define() - Browser
Source: https://github.com/jahilldev/component-elements/blob/main/packages/preactement/README.md
Register a custom element and render a Preact component in the browser. Supports dynamic imports for code splitting.
```APIDOC
## Using define() - In the browser
In order to register and render a component, you'll need to call `define()` with your chosen component, e.g:
```tsx
import { define } from 'preactement';
import { HeroBanner } from './heroBanner';
/*[...]*/
define('hero-banner', () => HeroBanner);
```
This registers `` as a custom element. When that element exists on the page, `preactement` will render our component.
If the custom element isn't present immediately, e.g it's created dynamically at some point in the future, we can provide an async function that explicitly resolves your component:
```tsx
define('hero-banner', () => Promise.resolve(HeroBanner));
```
This allows us to reduce the overall code in our bundle, and load the required component on demand when needed.
You can either resolve the component from your async function, as seen above, _or_ `preactement` will try to infer the export key based on the provided tag name. For example:
```tsx
import { define } from 'preactement';
/*[...]*/
define('hero-banner', () => import('./heroBanner'));
```
As the `heroBanner.ts` file is exporting the component as a key, e.g `export { HeroBanner };`, and this matches the tag name in kebab-case, e.g `hero-banner`, the component will be correctly rendered.
```
--------------------------------
### Defining a Custom Element with Options
Source: https://github.com/jahilldev/component-elements/blob/main/packages/preactement/README.md
Use the 'define' function to register a custom element, optionally providing configuration options.
```javascript
define('hero-banner', () => HeroBanner, {
/*[options]*/
});
```
--------------------------------
### define(name, component, options)
Source: https://context7.com/jahilldev/component-elements/llms.txt
Registers a custom element with the browser. The options object allows for prop transformation and component wrapping.
```APIDOC
## define(name, component, options)
### Description
Registers a React or Preact component as a custom element. The options object supports `formatProps` for data normalization and `wrapComponent` for HOC integration.
### Parameters
- **name** (string) - Required - The custom element tag name.
- **component** (function/promise) - Required - The component definition or a dynamic import.
- **options** (object) - Optional - Configuration object containing `formatProps` or `wrapComponent`.
### Options
- **formatProps** (function) - Optional - A function that transforms props before they are passed to the component. Useful for normalizing casing (e.g., PascalCase to camelCase).
- **wrapComponent** (function) - Optional - A function that wraps the component with a Higher Order Component (HOC), such as Redux Providers or ThemeProviders.
### Request Example
```javascript
define('user-profile', () => UserProfile, {
formatProps: (props) => { /* transform logic */ },
wrapComponent: (Component) => (props) =>
});
```
```
--------------------------------
### ES5 Browser Support with Polyfills
Source: https://context7.com/jahilldev/component-elements/llms.txt
For legacy browser support, such as IE11, import the ES5 build of the library and include the necessary Custom Elements polyfills at the top of your entry file.
```javascript
// At the very top of your entry file
import '@webcomponents/custom-elements';
import '@webcomponents/custom-elements/src/native-shim';
// Then import from the ES5 build
import { define } from 'reactement/es5';
// or
import { define } from 'preactement/es5';
// Use as normal
define('my-component', () => MyComponent);
```
--------------------------------
### Use define() for SSR
Source: https://github.com/jahilldev/component-elements/blob/main/packages/reactement/README.md
Generate a custom element container for server-side rendering.
```ts
define('hero-banner', () => HeroBanner);
```
```tsx
import { define } from 'reactement';
/*[...]*/
const Component = define('hero-banner', () => HeroBanner);
/*[...]*/
function HomePage() {
return (
);
}
```
--------------------------------
### Async Component Loading
Source: https://context7.com/jahilldev/component-elements/llms.txt
Enables lazy loading of components by providing a Promise-based loader to the define function, reducing initial bundle size.
```APIDOC
## Async Component Loading
### Description
By passing a dynamic import or a Promise to the component loader, the component code is fetched only when the custom element is rendered in the DOM.
### Usage Example
```tsx
// Dynamic import
define('hero-banner', () => import('./heroBanner'));
// Promise resolution
define('hero-banner', () => Promise.resolve(HeroBanner));
```
```
--------------------------------
### Register a component with define()
Source: https://github.com/jahilldev/component-elements/blob/main/packages/reactement/README.md
Register a custom element to render a React component in the browser.
```tsx
import { define } from 'reactement';
import { HeroBanner } from './heroBanner';
/*[...]*/
define('hero-banner', () => HeroBanner);
```
```tsx
define('hero-banner', () => Promise.resolve(HeroBanner));
```
```tsx
import { define } from 'reactement';
/*[...]*/
define('hero-banner', () => import('./heroBanner'));
```
--------------------------------
### Define an Async Preact Component for On-Demand Loading
Source: https://github.com/jahilldev/component-elements/blob/main/packages/preactement/README.md
Register a Preact component using an async function to enable on-demand loading. This reduces initial bundle size by loading the component only when needed. The function should return a Promise that resolves to the component.
```tsx
define('hero-banner', () => Promise.resolve(HeroBanner));
```
--------------------------------
### Async Component Loading
Source: https://context7.com/jahilldev/component-elements/llms.txt
Lazy-load components using async functions to reduce initial bundle size.
```tsx
import { define } from 'reactement';
// Method 1: Explicit Promise resolution
define('hero-banner', () => Promise.resolve(HeroBanner));
// Method 2: Dynamic import with auto-inference
// The component name is inferred from the tag name (hero-banner → HeroBanner)
define('hero-banner', () => import('./heroBanner'));
// Method 3: Dynamic import with named export
// heroBanner.ts exports: export { HeroBanner }
define('hero-banner', () => import('./heroBanner').then(m => m.HeroBanner));
// The component will only be loaded when appears in the DOM
```
--------------------------------
### Handle component children
Source: https://github.com/jahilldev/component-elements/blob/main/packages/reactement/README.md
Passing nested HTML as children to a component.
```html
Banner Title
```
```tsx
/*[...]*/
function HeroBanner({ children }) {
return {children};
}
```
--------------------------------
### Define a Preact Component with Dynamic Import
Source: https://github.com/jahilldev/component-elements/blob/main/packages/preactement/README.md
Register a Preact component using a dynamic import. Preactement can infer the component export if it matches the kebab-case tag name. This is another method for on-demand loading.
```tsx
import { define } from 'preactement';
/*[...]*/
define('hero-banner', () => import('./heroBanner'));
```
--------------------------------
### Pass Nested HTML as Children
Source: https://context7.com/jahilldev/component-elements/llms.txt
Shows how to pass nested HTML elements as the children prop, which are automatically converted to virtual DOM nodes.
```html
This paragraph becomes children
```
```tsx
import { define } from 'reactement';
interface HeroBannerProps {
title: string;
children?: React.ReactNode;
}
function HeroBanner({ title, children }: HeroBannerProps) {
return (
{title}
{children} {/* Renders:
This paragraph becomes children
*/}
);
}
define('hero-banner', () => HeroBanner);
```
--------------------------------
### Pass Props via Attributes
Source: https://context7.com/jahilldev/component-elements/llms.txt
Demonstrates passing data to custom elements using a JSON string in a props attribute or via registered custom HTML attributes.
```html
```
```tsx
import { define } from 'reactement';
interface HeroBannerProps {
bannerTitle: string;
bannerSubtitle?: string;
}
function HeroBanner({ bannerTitle, bannerSubtitle }: HeroBannerProps) {
return (
{bannerTitle}
{bannerSubtitle &&
{bannerSubtitle}
}
);
}
// Register custom attributes - they're converted from kebab-case to camelCase
define('hero-banner', () => HeroBanner, {
attributes: ['banner-title', 'banner-subtitle']
});
// banner-title becomes bannerTitle in props
// banner-subtitle becomes bannerSubtitle in props
```
--------------------------------
### define() - Register Custom Element
Source: https://context7.com/jahilldev/component-elements/llms.txt
Registers a custom element and maps it to a React or Preact component. The component is rendered when the custom element appears in the DOM.
```APIDOC
## define(tagName, componentLoader)
### Description
Registers a custom element tag name and associates it with a component loader function. The component is rendered within the custom element once it is detected in the DOM.
### Parameters
- **tagName** (string) - Required - A valid hyphenated custom element name (e.g., 'hero-banner').
- **componentLoader** (function) - Required - A function that returns the component or a Promise resolving to the component.
### Usage Example
```tsx
import { define } from 'reactement';
define('hero-banner', () => HeroBanner);
```
```
--------------------------------
### Define component props
Source: https://github.com/jahilldev/component-elements/blob/main/packages/reactement/README.md
Methods for passing props to components via JSON blocks, attributes, or custom attributes.
```html
```
```html
```
```html
```
```ts
define('hero-banner', () => HeroBanner, { attributes: ['title-text'] });
```
--------------------------------
### Format Props for Casing Conventions
Source: https://context7.com/jahilldev/component-elements/llms.txt
Use formatProps to transform incoming props, normalizing casing conventions between server data and component props. This is useful when server data uses PascalCase and the component expects camelCase.
```tsx
import { define } from 'reactement';
interface UserProfileProps {
firstName: string;
lastName: string;
emailAddress: string;
}
function UserProfile({ firstName, lastName, emailAddress }: UserProfileProps) {
return (
{firstName} {lastName}
{emailAddress}
);
}
// Server sends PascalCase props, component expects camelCase
const formatProps = (props: Record) => {
return Object.keys(props).reduce((result, key) => {
const camelKey = key.charAt(0).toLowerCase() + key.slice(1);
result[camelKey] = props[key];
return result;
}, {} as Record);
};
define('user-profile', () => UserProfile, { formatProps });
// HTML with PascalCase props from server:
//
// Props are transformed to camelCase before passing to component
```
--------------------------------
### Component Properties
Source: https://github.com/jahilldev/component-elements/blob/main/packages/preactement/README.md
Methods for defining properties for your Preact component when using custom elements.
```APIDOC
## Properties
If you're not running `preactement` on the server, you have several ways of defining props for your component.
#### 1. Nested block of JSON:
```html
```
#### 2. A `props` attribute (this must be an encoded JSON string)
```html
```
#### 3. Custom attributes
```html
```
You'll need to define your custom attributes up front when using `define()`, e.g:
```ts
define('hero-banner', () => HeroBanner, { attributes: ['title-text'] });
```
These will then be merged into your components props in camelCase, so `title-text` will become `titleText`.
```
--------------------------------
### Nested HTML as Children
Source: https://github.com/jahilldev/component-elements/blob/main/packages/preactement/README.md
How to pass nested HTML content to your component's `children` property.
```APIDOC
## HTML
You can also provide nested HTML to your components `children` property. For example:
```html
Banner Title
```
This will correctly convert the `
` into virtual DOM nodes for use in your component, e.g:
```tsx
/*[...]*/
function HeroBanner({ children }) {
return {children};
}
```
### Important
Any HTML provided to the custom element **must be valid**; As we're using the DOM's native parser which is quite lax, any html passed that is not properly sanitised or structured might result in unusual bugs. For example:
This will result in a Preact error:
```jsx
Hello
Hello
```
```
--------------------------------
### Define a Preact Component for SSR Hydration
Source: https://github.com/jahilldev/component-elements/blob/main/packages/preactement/README.md
Use define() to generate a functional component that can be used within your application for server-side rendering. This component will hydrate the Preact component on the client.
```ts
import { define } from 'preactement';
/*[...]*/
const Component = define('hero-banner', () => HeroBanner);
/*[...]*/
function HomePage() {
return (
);
}
```
--------------------------------
### Register React Custom Element
Source: https://context7.com/jahilldev/component-elements/llms.txt
Register a React component as a custom element using the define function.
```tsx
import { define } from 'reactement';
// Define a simple component
interface HeroBannerProps {
title: string;
subtitle?: string;
children?: React.ReactNode;
}
function HeroBanner({ title, subtitle, children }: HeroBannerProps) {
return (
{title}
{subtitle &&
{subtitle}
}
{children}
);
}
// Register the custom element
define('hero-banner', () => HeroBanner);
// Now use in HTML:
//
```
--------------------------------
### Pass Props via JSON Script Block
Source: https://context7.com/jahilldev/component-elements/llms.txt
Embed a JSON script block within the custom element to pass props, useful for SSR.
```html
```
```tsx
import { define } from 'reactement';
interface HeroBannerProps {
title: string;
subtitle: string;
buttonText: string;
}
function HeroBanner({ title, subtitle, buttonText }: HeroBannerProps) {
return (
{title}
{subtitle}
);
}
define('hero-banner', () => HeroBanner);
// Props from JSON block are automatically parsed and passed to component
```
--------------------------------
### Specifying Custom Attributes for Components
Source: https://github.com/jahilldev/component-elements/blob/main/packages/reactement/README.md
Define custom attributes that should be passed down to your component by listing them in the 'attributes' array within the options.
```javascript
define('hero-banner', () => HeroBanner, { attributes: ['banner-title'] });
```
--------------------------------
### Specifying Custom Attributes for a Component
Source: https://github.com/jahilldev/component-elements/blob/main/packages/preactement/README.md
Define custom attributes that should be passed down to your component using the 'attributes' option.
```javascript
define('hero-banner', () => HeroBanner, {
attributes: ['banner-title']
});
```
--------------------------------
### Component Props: parent
Source: https://context7.com/jahilldev/component-elements/llms.txt
Accessing the underlying custom element root from within the component.
```APIDOC
## Component Props: parent
### Description
All components defined via Reactement receive a `parent` prop by default, which references the custom element root. This allows for direct DOM manipulation or integration with Web Component APIs.
### Parameters
- **parent** (HTMLElement) - Optional - The root custom element instance.
### Request Example
```javascript
function Tooltip({ text, parent }) {
useEffect(() => {
if (parent) {
parent.classList.add('tooltip-initialized');
}
}, [parent]);
return
{text}
;
}
```
```
--------------------------------
### Using Slots in Custom Elements
Source: https://github.com/jahilldev/component-elements/blob/main/packages/preactement/README.md
Assign HTML content to component props using the slot attribute. Slot keys are normalized to camelCase.
```html
```
--------------------------------
### Passing Props via JSON Script Block
Source: https://context7.com/jahilldev/component-elements/llms.txt
Injects props into the component by embedding a JSON script block inside the custom element, ideal for SSR.
```APIDOC
## JSON Script Block Props
### Description
Embed a
```
```
--------------------------------
### Define Custom Attributes for Props
Source: https://github.com/jahilldev/component-elements/blob/main/packages/preactement/README.md
Register custom HTML attributes that will be mapped to component props. These attributes are defined in the options object passed to `define()`. The attribute names are converted to camelCase for the component's props.
```ts
define('hero-banner', () => HeroBanner, { attributes: ['title-text'] });
```
--------------------------------
### Pass Props via Nested JSON Script Tag
Source: https://github.com/jahilldev/component-elements/blob/main/packages/preactement/README.md
Provide component props by embedding a JSON object within a `
```
--------------------------------
### Pass Children to a Preact Component
Source: https://github.com/jahilldev/component-elements/blob/main/packages/preactement/README.md
Provide nested HTML content within the custom element, which will be passed as the `children` prop to the Preact component. Ensure the nested HTML is valid.
```html
Banner Title
```
--------------------------------
### Assign Named Content Blocks with Slots
Source: https://context7.com/jahilldev/component-elements/llms.txt
Uses the slot attribute to map specific HTML blocks to component props, with keys automatically converted to camelCase.
```html
*/}
{status === 'success' && successMessage}
{status === 'error' && errorMessage}
{status === 'idle' && (
)}
);
}
define('login-form', () => LoginForm);
```
--------------------------------
### Wrap Component with HOCs
Source: https://context7.com/jahilldev/component-elements/llms.txt
The wrapComponent option allows you to wrap your component with Higher Order Components (HOCs) before rendering. This is useful for integrating context providers like Redux or theme providers.
```tsx
import { define } from 'reactement';
import { Provider } from 'react-redux';
import { ThemeProvider } from 'styled-components';
import { store } from './store';
import { theme } from './theme';
interface DashboardProps {
userId: string;
}
function Dashboard({ userId }: DashboardProps) {
// Component can now access Redux store and theme
return
Dashboard for user {userId}
;
}
// Wrap component with Redux Provider and ThemeProvider
const wrapComponent = (Component: React.ComponentType) => {
return (props: any) => (
);
};
define('app-dashboard', () => import('./Dashboard'), { wrapComponent });
```
--------------------------------
### Register Preact Custom Element
Source: https://context7.com/jahilldev/component-elements/llms.txt
Register a Preact component as a custom element using the define function.
```tsx
import { define } from 'preactement';
import { h, Fragment } from 'preact';
import { useState } from 'preact/hooks';
interface CounterProps {
initialCount?: number;
parent?: HTMLElement;
}
function Counter({ initialCount = 0, parent }: CounterProps) {
const [count, setCount] = useState(initialCount);
return (
Count: {count}
);
}
// Register the custom element
define('app-counter', () => Counter);
// HTML usage:
//
```
--------------------------------
### Define a Preact Component as a Custom Element
Source: https://github.com/jahilldev/component-elements/blob/main/packages/preactement/README.md
Register a Preact component with a custom HTML tag. The component will be rendered when the custom element is encountered in the DOM. Ensure your component is imported correctly.
```tsx
import { define } from 'preactement';
import { HeroBanner } from './heroBanner';
/*[...]*/
define('hero-banner', () => HeroBanner);
```
--------------------------------
### Pass Props via Encoded JSON 'props' Attribute
Source: https://github.com/jahilldev/component-elements/blob/main/packages/preactement/README.md
Pass component props as a JSON string to the 'props' attribute of the custom element. The JSON string must be properly encoded.
```html
```
--------------------------------
### Accessing Parent Element in Components
Source: https://context7.com/jahilldev/component-elements/llms.txt
Components automatically receive a 'parent' prop, which is a reference to the root custom element. This prop is useful for DOM manipulation or integrating with Web Component APIs.
```tsx
import { define } from 'reactement';
import { useEffect } from 'react';
interface TooltipProps {
text: string;
parent?: HTMLElement;
}
function Tooltip({ text, parent }: TooltipProps) {
useEffect(() => {
if (parent) {
// Add custom styling or attributes to the parent custom element
parent.classList.add('tooltip-initialized');
parent.setAttribute('role', 'tooltip');
}
}, [parent]);
return (
{text}
);
}
define('app-tooltip', () => Tooltip);
```
--------------------------------
### Invalid HTML for Custom Element Children
Source: https://github.com/jahilldev/component-elements/blob/main/packages/preactement/README.md
Passing invalid or unsanitized HTML as children to a custom element can lead to Preact errors. Ensure all nested HTML is well-formed and valid.
```jsx
{isLoggedIn && successMessage}
);
}
```
--------------------------------
### Accessing Children in a Preact Component
Source: https://github.com/jahilldev/component-elements/blob/main/packages/preactement/README.md
The `children` prop passed from the custom element's nested HTML can be rendered within the Preact component. This allows for composition and passing complex content.
```tsx
/*[...]*/
function HeroBanner({ children }) {
return {children};
}
```
--------------------------------
### HTML Structure Resulting in Unexpected Tag
Source: https://github.com/jahilldev/component-elements/blob/main/packages/preactement/README.md
Improperly structured HTML, even if it appears to be a self-closing tag, can be parsed by the DOM into unexpected elements, potentially causing rendering issues. Ensure correct tag closure.
```jsx
Hello
Hello
```
=== COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.