npm.io
0.6.0-alpha.1 • Published 3 years ago

compostate-element

Licence
MIT
Version
0.6.0-alpha.1
Deps
0
Size
40 kB
Vulns
0
Weekly
0
Stars
35

compostate-element

Web Components bindings for compostate

NPM JavaScript Style Guide

Install

npm install --save compostate compostate-element
yarn add compostate compostate-element
pnpm add compostate compostate-element

Usage

import { ref, effect } from 'compostate';
import { setRenderer, define } from 'compostate-element';
import { render, html } from 'lit-html';

// Setup the element's renderer using Lit
// Any renderer should work
setRenderer((root, result) => {
  render(result, root);
});

// Define an element
define({
  // Name of the element (required)
  name: 'counter-title',
  // Props to be tracked (required)
  props: ['value'],
  // Element setup
  setup(props) {
    // The setup method is run only once
    // it's useful to setup your component logic here.
    effect(() => {
      // Props are reactive
      console.log(`Current count: ${props.value}`);
    });

    // Return the template atom
    // The template's returned value depends
    // on the renderer's templates.
    // For example, you can return a JSX markup
    // if the renderer used is React or Preact.
    return () => (
      html`
        <h1>Count: ${props.value}</h1>
      `
    );
  },
});

define({
  name: 'counter-button',
  setup() {
    const count = ref(0);

    function increment() {
      count.value += 1;
    }

    function decrement() {
      count.value -= 1;
    }

    return () => (
      html`
        <button @click=${increment}>Increment</button>
        <button @click=${decrement}>Decrement</button>
        <counter-title value="${count.value}"></counter-title>
      `
    );
  },
});

License

MIT lxsmnsyc