Making Framework Agnostic Web Components with StencilJS

The Problem

Install

Run Dev Server

Folder Structure

src

ASSETS

COMPONENTS

GLOBAL

www

Anatomy of a Component

app-component.css

app-component.e2e.ts

app-component.ts

Creating a new component

import { Component, Host, h } from '@stencil/core';@Component({
tag: 'app-button',
styleUrl: 'app-button.css',
shadow: true,
})
export class AppButton {
render() {
return (
<Host>
<slot></slot>
</Host>
);
}
}

State and Props

import { Component, Host, h, Prop, State } from '@stencil/core';@Component({
tag: 'app-button',
styleUrl: 'app-button.css',
shadow: true,
})
export class AppButton {
@Prop() word:string;
@State() count:number = 1;
render() {
return (
<Host>
<button>{this.word} {this.count}</button>
</Host>
);
}
}
@Component({
tag: 'app-home',
styleUrl: 'app-home.css',
shadow: true,
})
export class AppHome {
render() {
return (
<div class="app-home">
<p>
Welcome to the Stencil App Starter. You can use this starter to build entire apps all with web components using Stencil! Check out our docs on{' '}
<a href="https://stenciljs.com">stenciljs.com</a> to get started.
</p>
<app-button word="Click Me"/> <stencil-route-link url="/profile/stencil">
<button>Profile page</button>
</stencil-route-link>
</div>
);
}
}

Events

import { Component, Host, h, Prop, State } from '@stencil/core';@Component({
tag: 'app-button',
styleUrl: 'app-button.css',
shadow: true,
})
export class AppButton {
@Prop() word: string;
@State() count: number = 1;
render() {
return (
<Host>
<button
onClick={() => {
this.count += 1;
console.log(this.count);
}}
>
{this.word} {this.count}
</button>
</Host>
);
}
}

Keep On Learning

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store