Home > database >  How to properly parse Sub-components in the Stancil.js component
How to properly parse Sub-components in the Stancil.js component

Time:06-11

I am trying to use Stencil.js to create tabs component with the following structure:

<custom-tabs>
    <custom-tab active label="Label 1">
        Some generic HTML content <custom-rating value="4"></custom-rating>
    </custom-tab>
    <custom-tab active label="Label 2">
        Some more generic HTML content <custom-rating value="5"></custom-rating>
    </custom-tab>
</custom-tabs>

The parent component needs to render the underlying HTML by parsing each 'custom-tab' component (which doesn't have the render method) and extracting the 'label' parameter from each tab, building the navigation list of those labels and similarly extracting the main content of the each tab and displaying in in the corresponding panel of the tab.

In my parent component I grab the tabs in the 'componentWillLoad' hook

componentWillLoad() {
    // Grab tabs from this component
    this.tabs = Array.from(this.el.querySelectorAll('custom-tab'));
    console.log(this.tabs);
  }

and then in render function I try to output the contents:

return (
      <div>
        {this.tabs.map((tab: HTMLCustomTabElement, index: number) => {
          return (
            <div
              role="tab"
              onClick={() => this.openTab(index)}>
              {tab.label} {tab.innerHTML}
            </div>
          );
        })}
      </div>
    );

The problem is tab.innerHTML is not parsing the custom-rating component and just outputs it as text. Could you please suggest the right way to display the tab's content so that everything is parsed properly?

CodePudding user response:

You can output HTML by setting the innerHTML property:

return (
  <div>
    {this.tabs.map((tab: HTMLCustomTabElement, index: number) => {
      return (
        <div
          role="tab"
          onClick={() => this.openTab(index)}>
          {tab.label}
          <div innerHTML={tab.innerHTML}></div>
        </div>
      );
    })}
  </div>
);

  • Related