How could I get the slots and the other elements to render?
This is the render function of my Stencil component:
import {Component, h, Element, State} from "@stencil/core"
@Component({
tag: 'base-offcanvas',
styleUrl: 'base-offcanvas.css',
shadow: false,
})
export class BaseOffcanvas{
@Element() container: HTMLElement;
@State() isOpen = true;
close = () => {
console.log('close');
this.isOpen = false;
};
open = () => {
this.isOpen = true;
this.container.focus();
};
checkFocus = (e: KeyboardEvent) => {
if (e.key === 'Escape') {
this.close();
}
if (document.activeElement.closest('.offcanvas') === null) {
this.container.focus();
}
};
render() {
return (
<section ref={el => this.container = el} class={`offcanvas bg-white ${this.isOpen ? 'open' : 'closed'}`} tabIndex={-1} onKeyUp={this.checkFocus}>
<div class="offcanvas-header">
<slot name="heading" />
</div>
<button type="button" onClick={this.close}>X</button>
<div class="offcanvas-content">
<slot name="content" />
</div>
</section>
);
}
}
This is me using it
<base-offcanvas>
<h2 slot="heading">Offcanvas Header</h2>
<p slot="content">Offcanvas content goes here</p>
</base-offcanvas>
All that is rendered is the following and it doesn't include the section tag or button or wrapping divs and I'm wondering why.
<base-offcanvas class="hydrated">
<!---->
<h2 slot="heading">Offcanvas Header</h2>
<p slot="content">Offcanvas content goes here</p>
</base-offcanvas>
I want all the other content in that render method to show up and the slots as well.
I tried adding named slots and expected other markup to exist alongside it.
The property decorated with
@Element()is readonly. It is used to create a reference to the component host element, not for elements in general. Because you are trying to setcontainerviarefin your render function, this throws an error which prevents the render from completing which is why you don't see the component rendered. Most likely you should see an error in the browser console.Change
@Element() container: HTMLElement;tocontainer: HTMLElement;and it should work.