Web component Light DOM slot equivalent for injecting dynamic content into specific element

28 Views Asked by At

Im struggling to do something that seems like it should be simple. I am creating my first web component and it cannot be within the shadowDOM. I need it to receive some dynamic content and inject it into the correct div like so:

<component>
  <div id="one"><!-- Dynamic Content ends up here --></div>
  <div id="two">...</div>
</component>

This is simple using slots in shadowDOM, why is it proving difficult in lightDOM? Any help is appreciated.

1

There are 1 best solutions below

0
Harshal Patil On

You problem is essentially about using slots without Shadow DOM. Unfortunately, there is no out-of-box solution for this problem. You can use combination of <template> tag and component props:

<component>
  <template>
      <div id="one"><!-- Dynamic Content ends up here --></div>
      <div id="two">...</div>
  </template>
</component>

And, then for each instance of the <component />, you will clone the template using cloneNode method. And, then you append this Node as a child of your custom component. You can augment the DOM however you like.

Now, second part of the equation is adding the dynamic content to the div#one and div#two. For this purpose, you should declare the two props over the component and the caller will pass the content. The web component will then append that content via DocumentFragment, innerHTML or other DOM APIs. This is roughly similar to what vDOM based frameworks like React, Vue do. The only difference is instead of passing real DOM, it passes virtual tree as a children or render prop.

So, without a proper framework, this is a lot of work. I would recommend you consider using Shadow DOM and keep the Shadow Root open.