Quick-start guide
Getting started
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| 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> ) } }
|
HTML
1
| <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.
DOM events
1 2 3 4 5 6 7 8 9 10 11 12 13
| export class MyComponent { render () { return ( <input onChange={(event: UIEvent) => this.inputChanged(event)} /> ) }
inputChanged (event) { console.log('input changed:', event.target.value) } }
|
Stencil uses DOM events.
See: Handling user input
Multiple children
1 2 3 4 5 6
| render () { return [ <h1>Hello there</h1>, <p>This component returns multiple nodes</p> ] }
|
render() can return an array of elements.
See: Complex template content
State
Managing state
1 2 3 4 5 6 7
| export class MyComponent { @State() isVisible: boolean
show () { this.isVisible = true } }
|
Just do assignments. You can’t do mutations though, see next section.
See: Managing component state
Updating arrays and objects
✗ Bad
1 2
| this.names.push('Larry') this.options.show = true
|
✓ OK
1 2
| 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
Slots
Using slot
1 2 3
| <my-component> <span>Hello, friends</span> </my-component>
|
Component
1 2 3
| render() { return <h1><slot /></h1> }
|
You can pass JSX/HTML as child elements. Use the slot tag to use them inside your component.
See: Slots
Multiple slots
1 2 3 4
| <my-component> <p slot='my-header'>Hello</p> <p slot='my-footer'>Thanks</p> </my-component>
|
Component
1 2 3 4 5 6
| render () { return <div> <header><slot name='my-header' /></header> <footer><slot name='my-footer' /></footer> </div> }
|
See: Slots
Lifecycle
Lifecycle hooks
| Event |
Description |
componentWillLoad() |
Before rendering |
componentDidLoad() |
After rendering |
| — |
— |
componentWillUpdate() |
Before updating |
componentDidUpdate() |
After updating |
| — |
— |
componentDidUnload() |
After unmounting |
See: Component lifecycle
Example
1 2 3 4 5
| export class MyComponent { componentWillUpdate () { console.log('updating') } }
|
References