title | category | layout | updated | keywords | intro | ||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
Stencil |
JavaScript libraries |
2017/sheet |
2017-10-11 |
|
[Stencil](https://github.com/ionic-team/stencil) is a compiler for web components made by the Ionic team. This guide targets Stencil v0.0.5.
|
{: .-three-column}
{: .-prime}
import { Component, Prop, State } from '@stencil/core'
@Component({
tag: 'my-component',
styleUrl: 'my-component.scss'
})
export class MyComponent {
@Prop() name: string
@State() isVisible: boolean = true
render () {
return <p>I am {this.name}!</p>
)
}
}
<my-component name='Groot' />
That's the same example in the Readme, that's as simple as you can get! Just use <my-component>
like you would use any other HTML tag.
export class MyComponent {
render () {
return (
<input
onChange={(event: UIEvent) => this.inputChanged(event)}
/>
)
}
inputChanged (event) {
console.log('input changed:', event.target.value)
}
}
{: data-line="5,10,11"}
Stencil uses DOM events.
See: Handling user input
render () {
return [
<h1>Hello there</h1>,
<p>This component returns multiple nodes</p>
]
}
{: data-line="3,4"}
render()
can return an array of elements.
export class MyComponent {
@State() isVisible: boolean
show () {
this.isVisible = true
}
}
{: data-line="4,5"}
Just do assignments. You can't do mutations though, see next section.
this.names.push('Larry') // ⚠️
this.options.show = true // ⚠️
this.names = [ ...this.names, 'Larry' ]
this.options = { ...this.options, show: true }
Mutable operations such as push()
won't work. You'll need to assign a new copy.
See: Updating arrays
<my-component>
<span>Hello, friends</span>
</my-component>
{: data-line="2"}
render() {
return <h1><slot /></h1>
}
{: data-line="2"}
You can pass JSX/HTML as child elements. Use the slot
tag to use them inside your component.
See: Slots
<my-component>
<p slot='my-header'>Hello</p>
<p slot='my-footer'>Thanks</p>
</my-component>
{: data-line="2,3"}
render () {
return <div>
<header><slot name='my-header' /></header>
<footer><slot name='my-footer' /></footer>
</div>
}
{: data-line="3,4"}
See: Slots
Event | Description |
---|---|
componentWillLoad() |
Before rendering |
componentDidLoad() |
After rendering |
--- | --- |
componentWillUpdate() |
Before updating |
componentDidUpdate() |
After updating |
--- | --- |
componentDidUnload() |
After unmounting |
See: Component lifecycle
export class MyComponent {
componentWillUpdate () {
console.log('updating')
}
}
- Stencil docs (stenciljs.com)