DEV Community

Unpublished Post. This URL is public but secret, so share at your own discretion.

Dynamic Unorderlist web component generate using stencilJS

Using stenciljs dynamically generate nesting unordered <ul><li>...</li></ul> list, so i and giving input as a Obj={} i am getting some issues. Here is my code below Please help me on this...

1. index.html

<!DOCTYPE html>
<html dir="ltr" lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=5.0">
  <title>Stencil Component Starter</title> 
  <script src="/build/mycomponent.js"></script>

</head>
<body>   
  <list-component list-object='[
  {title: "Point", children: [
      {title: "Point"},
      {title: "Point"},
      {title: "Point"},
      {title: "Point", children: [
          {title: "Point"},
          {title: "Point"},
          {title: "Point"}
      ]}
  ]},
  {title: "Point", children: [
      {title: "Point"},
      {title: "Point", children: [
          {title: "Point"},
          {title: "Point"},
          {title: "Point"}
      ]},
      {title: "Point"}
  ]},
]' > </list-component>  
</body>
</html>

ISSUE: I am passing nested object to the custom web component. In this list.tsx file i am facing problem while passing arguments to the function buildList("?","?")...?


2. list.tsx


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


@Component({
    tag:'list-component',
    styleUrl:'./list-component.css' 
})

export class ListComponent{

    @State() idName: string;   
    @Prop() listObject: string;
    @Element() flashElement: HTMLElement;   

    private ulContent: HTMLElement;

    componentWillLoad() { 
        this.ulContent  = this.flashElement.querySelector('.ul-content');
        this.buildList(this.ulContent,this.listObject);  
    }


    @Watch('listObject') 
    buildList(parentElement, listObject){ 
        console.log(listObject);
        var i, l, list, li, ul1;
        if( !listObject || !listObject.length ) { return; } 
        ul1 = document.createElement('ul');
        list = parentElement.appendChild(ul1);
        for(i = 0, l = listObject.length ; i < l ; i++) {
            li = document.createElement('li');
            li.appendChild(document.createTextNode(listObject[i].title)); 
            list.appendChild(li);
            this.buildList(li, listObject[i].children);
        } 
    } 

    render() {
        return ( 
            <div class="ul-content"></div>
        );
    }
}

Top comments (0)