Search code examples
web-componentstenciljs

How to correctly nest slots in child elements when using Stencil.js?


I know that if I have a <slot /> inside my component, I can then insert content from the HTML, but I don't understand how this works.

For example:

      render() {
        return(
          <div>
            <slot />
          </div>
        )
      }

Now, inside my HTML, I can do this:

<my-card>test</my-card>

and "test" will be inserted as a content.

However, if the <slot /> is nested inside other child-elements inside my component, the "test" text is still inserted even if it's not inside those particular elements. How does that work?

For example:

      render() {
        return(
          <div>
            <button><slot /></button>
            <select>
              <option value="one"><slot /></option>
            </select>
            <p><slot /></p>
          </div>
        )
      }

Now, in my HTML, if I do this:

<my-card>test</my-card>

The text "test" is inserted inside the <slot /> inside the button. But what if I want to add text inside the <option> <slot />? How do I do that?

If I only have one <slot /> inside <option> for example, how do I insert text inside of it from my HTML?


Solution

  • As mentioned in the comments, you can only have a single unnamed slot. Any additional slots have to have a name:

    <slot name="outside" />
    

    To add an element inside a named slot you can use the slot attribute:

    <my-card>
      <span slot="outside">test</span>
    </my-card>
    

    See also Stencil's documentation on slots.