Quick Start Guide
Component Definition
import { Component, Prop, State, h } from '@stencil/core'
@Component({
tag: 'my-component',
styleUrl: 'my-component.scss',
shadow: true
})
export class MyComponent {
@Prop() name: string
@State() isVisible: boolean = true
render() {
return <p>I am {this.name}!</p>
}
}
<my-component name="Groot"></my-component>
Handling DOM Events
export class MyComponent {
inputChanged(event: UIEvent) {
console.log('input changed:', (event.target as HTMLInputElement).value)
}
render() {
return (
<input onChange={(e: UIEvent) => this.inputChanged(e)} />
)
}
}
Returning Multiple Child Nodes
render() {
return [
<h1>Hello there</h1>,
<p>This component returns multiple root nodes</p>
]
}
State Management
Updating State
export class MyComponent {
@State() isVisible: boolean = false
show() {
this.isVisible = true
}
}
Immutability for Arrays and Objects
Avoid In-place Mutation
// Avoid in-place mutations
this.names.push('Larry')
this.options.show = true
Create New References
// Trigger re-render by assigning new instances
this.names = [...this.names, 'Larry']
this.options = { ...this.options, show: true }
Slots
Default Slot
<my-component>
<span>Hello, friends</span>
</my-component>
render() {
return <h1><slot /></h1>
}
Named Slots
<my-component>
<p slot="my-header">Header Content</p>
<p slot="my-footer">Footer Content</p>
</my-component>
render() {
return (
<div>
<header><slot name="my-header" /></header>
<footer><slot name="my-footer" /></footer>
</div>
)
}
Lifecycle Hooks
| Lifecycle Hook | Timing / Description |
|---|---|
componentWillLoad() |
Called once before the first render |
componentDidLoad() |
Called once after the initial render |
componentWillUpdate() |
Called before re-rendering due to state/prop change |
componentDidUpdate() |
Called after re-rendering completed |
disconnectedCallback() |
Called when the element is removed from the DOM |