stencil-reflector

Reflect decorated properties back stencil components to keep them synchronized

Usage no npm install needed!

<script type="module">
  import stencilReflector from 'https://cdn.skypack.dev/stencil-reflector';
</script>

README

stencil-reflector

Reflects properties decorated with @reflect back to their parent stencil components.

Why reflect?

Stencil only compares references for changes, and will not re-render when data inside of an array or object changes. [1]

stencil-reflector is a minimalistic approach of solving the synchronisation issues when working with instances as properties of stencil web components.

Properties decorated with @reflect will cause the component to re-render. And that's about it.

Install

npm install stencil-reflector --save-dev

...or copy the decorator from index.ts, it's just a few lines of code.

Example

Todo.ts

class Todo extends Reflector {
    @reflect text: string;
    @reflect isDone: boolean;
    
    complete(){
        // will re-render <my-component/>
        this.isDone = true;
    }
}

my-components.ts

@Component({
    tagName: 'my-component'
})
export class MyComponent {
    @Element() el: HTMLStencilElement;
    
    todo: Todo;
    
    componenWillLoad(){
        // instances of Reflector require the components element as first parameter
        this.todo = new Todo(this.el, {
            text: 'Implement stencil-reflector',
            isDone: false
        });
    }
    
    render(){
        return [
            todo.text,
            todo.isDone ? 'completed' :
                <input type="checkbox" onInput={() => todo.complete()} />
        ]
    }
}

API

@reflect

Indicates that any change on the property should reflect back to the component. Requires the instance to have the component assigned to this.el.

Reflector

Can be used to inherit classes from, but is not required as long as this.el equals the HTMLStencilElement.

class Todo extends Reflector {}
const todo = new Todo(myComponentElement);
console.log('Will reflect decorated properties to:',todo.el);

Thanks to