Skip to content
pionjsPublic

About

React's Hooks API implemented for web components

Topics

Resources

Code of conduct

Stars

131 stars

Watchers

1 watching

Forks

Repository files navigation

pion

npm npm coverage

React's Hooks API but for standard web components and lit-html or hyperHTML. Forked from haunted.

📚 Read the Docs 📖

<html lang="en">
  <my-counter></my-counter>

  <script type="module">
    import { html } from 'https://unpkg.com/lit?module';
    import { component, useState } from 'https://unpkg.com/@pionjs/pion';

    function Counter() {
      const [count, setCount] = useState(0);

      return html`
        <div id="count">${count}</div>
        <button type="button" @click=${() => setCount(count + 1)}>
          Increment
        </button>
      `;
    }

    customElements.define('my-counter', component(Counter));
  </script>
</html>

More example integrations can be found in this gist.

Hooks

pion supports the same API as React Hooks. The hope is that by doing so you can reuse hooks available on npm simply by aliasing package names in your bundler's config.

Currently pion supports the following hooks:

Function Signatures

// Or another renderer, see Guides
type Renderer = (element: Element) => TemplateResult;

interface Options {
  baseElement: HTMLElement;
  observedAttributes: string[];
  useShadowDOM: boolean;
  shadowRootInit: ShadowRootInit;
  styleSheets: (CSSStyleSheet | string)[];
}

declare function component(
  renderer: Renderer,
  options: Options
): Element;

declare function component<BaseElement = HTMLElement>(
  renderer: Renderer,
  baseElement: BaseElement,
  options: Options
): Element

declare function virtual(renderer: Renderer): Directive

Native properties and ARIA

Observed attributes whose name maps to a native reflected property (aria-*, title, lang, dir) re-render on change. Read their values in the renderer with getAttribute — the attribute holds the verbatim value:

customElements.define('my-toggle', component(
  // aria-expanded=${host.ariaExpanded} — camelCase reads go through the
  // property, which can coerce; the attribute never does
  (host) => html`<div aria-expanded=${host.getAttribute('aria-expanded')}>…</div>`,
  { observedAttributes: ['aria-expanded'] },
));

License

BSD-2-Clause

About

React's Hooks API implemented for web components

Topics

Resources

Code of conduct

Stars

131 stars

Watchers

1 watching

Forks

Releases

Packages

Used by

Contributors

Languages