Stencil.js renders slot content, event if the render() returns null

Viewed 4364

I have a Stencil.JS components:

import {Component, Prop, h} from '@stencil/core';

@Component({
   tag: 'my-comp',
   styleUrl: 'my-comp.css',
   // shadow: true
})

export class MyComp {
   @Prop() active: boolean = false;
   render() {
      return this.active ? <div>
         <slot></slot>
      </div> : null;
   }
}

I expect that content of the slot is not rendering when I use the component in this manner:

<my-comp>
   <p>I'm hidden!</p>
</my-comp>

And, actually it works as expected, when "shadow" set to true in Component decorator. But, when the shadow DOM is disabled, component shows the content of slot regardless of the value of this.active.

I have a feeling that I don't understand how the render works with slots. Could you please explain it to me? I would really appreciate If you know how to work-around this issue without hiding the slot content programatically.

2 Answers

The accepted answer is incorrect. Stencil absolutely supports <slot>, even in non-shadow components. That is how content projection works in Stencil.

There are a few caveats; the <slot> elements themselves are not actually rendered by Stencil in lightdom components, they serve only as location markers for where Stencil places children.

Additionally, pursuant to this question, conditionally rendering slots is not supported:
https://github.com/ionic-team/stencil/issues/399

We use <slot> in Stencil lightdom components, and have essentially fallen back on toggling display: none on a wrapper around the <slot> for this purpose. It's not ideal, but it works.

Related