How to inject props into dynamically rendered components via slot in stenciljs

In Stencil, from a parent component you might have a need to pass props into components that are going to be dynamically rendered using Slot tag.

In our example we have a root component that needs to pass a config prop to all the components that’ll get rendered inside root-container.

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

@Component({
  tag: 'root-component',
})
export class RootComponent {
  @Element() el: HTMLElement;
  @Prop() config: any;

  componentWillLoad() {
    // Inject config in all Slotted elements
    this.el.childNodes.forEach(element => {
      element["config"] = this.config;
    });
  }

  render() {
    return (
      <div class="root-container">
        <slot />
      </div>
    );
  }
}

A child component that is going to use the config for its working.

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

@Component({
  tag: 'child-component',
})
export class ChildComponent {
  @Prop() config: any;

  componentWillLoad() {
    // This component will get access
    // to config if slotted inside root.
    console.log(this.config);
  }

  render() {
    return (
      <div class="child-container">
        <h1>Child component</h1>
      </div>
    );
  }
}

Usage:

  // my-component.tsx

  render() {
    return (
      <root-component config={{data: {a: 1}}}>
        <child-component />
        <child-component />
      </root-component>
    );
  }

Want to hear when I write or build new stuff?

Subscribe to get my latest content by email.

    Comments