Skip to content

codewithkyle/supercomponent

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

28 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Super Components

Give your Web Components modern-day superpowers:

  • create stateful web components similar to React
  • manage your components state with an xstate inspired state machine
  • bring your own client-side rendering framework/library such as lit-html
  • works in every major browser
  • lightweight (483 bytes)

Installation

Install via NPM

npm i -S @codewithkyle/supercomponent

Import via CDN

import SuperComponent from "https://unpkg.com/@codewithkyle/supercomponent@2/supercomponent.min.mjs";

Usage

import SuperComponent from "@codewithkyle/supercomponent";

type ExampleModel = {
    products: Array<any>;
}
class Example extends SuperComponent<ExampleModel>{
    constructor(){
        super();
        this.state = "LOADING";
        this.stateMachine = {
            LOADING: {
                SUCCESS: "IDLING",
                ERROR: "ERROR",
            },
            IDLING: {
                TOGGLE: "LOADING",
            }
        }

        // Set the model & trigger the first render
        this.set({
            products: [],
        });
    }

    override async connected(){
        const request = await fetch("/products.json");
        if (request.ok){
            const response = await request.json();

            // Updates the model
            this.set({ products: response });

            // Trigger a state transition
            this.trigger("SUCCESS");
        } else {
            this.trigger("ERROR");
        }
    }

    override disconnected() {
        // Do something when the component disconnects from the DOM
    }

    override render(returnMarkup = false) {
        // Render this component model using any UI framework
        switch (this.state){
            case "ERROR":
                // Render error message
                break;
            case "IDLING":
                // Render this.model.products
                break;
            default:
                // Render loading animation
                break;
        }
    }
}
customElements.define("example-component", Example);

About

Give your Web Components modern-day superpowers.

Resources

License

Stars

Watchers

Forks