DEV Community

Cover image for 10 Caveats You May Face While Working With Web Components
Chad Adams
Chad Adams

Posted on • Originally published at cadamsdev.com

10 Caveats You May Face While Working With Web Components

Web Components have been around for a while, promising a standardized way to create reusable custom elements. It's clear that while Web Components have made significant strides, there are still several caveats that developers may face while working with them. This blog will explore 10 of these caveats.

1. Framework-Specific Issues

If you're deciding whether or not to use web components in your project. It's important to consider if web components is fully supported in your framework of choice or you may run into some unpleasant caveats.

Angular

For example to use web components in Angular it's required to add CUSTOM_ELEMENTS_SCHEMA to the module import.

@NgModule({
  schemas: [CUSTOM_ELEMENTS_SCHEMA],
})
export class MyModule {}
Enter fullscreen mode Exit fullscreen mode

The problem with using CUSTOM_ELEMENTS_SCHEMA is that Angular will opt out of type checking and intellisense for custom elements in the templates. (see issue)

To workaround this problem you could create an Angular wrapper component.

Here's an example of what that would look like.

@Component({
  selector: 'some-web-component-wrapper',
  template: '<some-web-component [someProperty]="someClassProperty"></some-web-component>
})
export class SomeWebComponentWrapper {
  @Input() someClassProperty: string;
}

@NgModule({
    declarations: [SomeWebComponentWrapper],
    exports: [SomeWebComponentWrapper],
    schemas: [CUSTOM_ELEMENTS_SCHEMA]
})
export class WrapperModule {}
Enter fullscreen mode Exit fullscreen mode

This works but it's not a good idea to create these manually. Since that creates a lot of maintenance and we can run into out of sync issues with the api. To make this less tedious. Both Lit (see here) and Stencil (see here) provide a cli to create these automatically. However the need to create these wrapper components in the first place is additional overhead. If the framework of your choice properly supports web components you shouldn't have to create wrapper components.

React

Another example is with React. Now React v19 was just released which addressed these issues. However, if you're still on v18 just note that v18 does not fully support web components. So here's a couple of issues you may face while working with web components in React v18. This is taken directly from the Lit docs.

"React assumes that all JSX properties map to HTML element attributes, and provides no way to set properties. This makes it difficult to pass complex data (like objects, arrays, or functions) to web components."

"React also assumes that all DOM events have corresponding "event properties" (onclick, onmousemove, etc), and uses those instead of calling addEventListener(). This means that to properly use more complex web components you often have to use ref() and imperative code."

For React v18 Lit recommends using their wrapper components because they fix the issues with setting the properties and listening for events for you.

Here's an example of a React wrapper component using Lit.

import React from 'react';
import { createComponent } from '@lit/react';
import { MyElement } from './my-element.js';

export const MyElementComponent = createComponent({
  tagName: 'my-element',
  elementClass: MyElement,
  react: React,
  events: {
    onactivate: 'activate',
    onchange: 'change',
  },
});
Enter fullscreen mode Exit fullscreen mode

Usage

<MyElementComponent
  active={isActive}
  onactivate={(e) => setIsActive(e.active)}
  onchange={handleChange}
/>
Enter fullscreen mode Exit fullscreen mode

Luckily with React v19 you shouldn't need to create wrapper components anymore. Yay!

The use of Web Components in micro frontends has revealed an interesting challenge:

2. Global Registry Issues

One significant problem is the global nature of the Custom Elements Registry:

If you're using a micro frontend and plan to use web components to reuse UI elements across each app you'll most likely run into this error.

Uncaught DOMException: Failed to execute 'define' on 'CustomElementRegistry':
the name "foo-bar" has already been used with this registry
Enter fullscreen mode Exit fullscreen mode

This error occurs when trying to register a custom element with a name that's already been used. This is common in micro frontends because each app in a micro frontend shares the same index.html file and each app tries to define the custom elements.

There is a proposal to address this called Scoped Custom Element Registries but there's no ETA so unfortunately you'll need to use a polyfill.

If you don't use the polyfill one workaround is to manually register the custom elements with a prefix to avoid naming conflicts.

To do this in Lit, you can avoid using the @customElement decorator which auto registers the custom element. Then add a static property for the tagName.

Before

@customElement('simple-greeting')
export class SimpleGreeting extends LitElement {
  render() {
    return html`<p>Hello world!</p>`;
  }
}
Enter fullscreen mode Exit fullscreen mode

After

export class SimpleGreeting extends LitElement {
  static tagName = 'simple-greeting';

  render() {
    return html`<p>Hello world!</p>`;
  }
}
Enter fullscreen mode Exit fullscreen mode

Then in each app you define the custom element with a prefix of the app name.

[SimpleGreeting].forEach((component) => {
  const newTag = `app1-${component.tagName}`;
  if (!customElements.get(newTag)) {
    customElements.define(newTag, SimpleGreeting);
  }
});
Enter fullscreen mode Exit fullscreen mode

Then to use the custom element you would use it with the new prefix.

<app1-simple-greeting></app1-simple-greeting>
Enter fullscreen mode Exit fullscreen mode

This works as a quick short term solution, however you may notice it's not the best developer experience so it's recommended to use the Scoped Custom Element Registry polyfill.

3. Inherited Styles

The Shadow DOM, while providing encapsulation, comes with its own set of challenges:

Shadow dom works by providing encapsulation. It prevents styles from leaking out of the component. It also prevents global styles from targeting elements within the component's shadow dom. However styles from outside the component can still leak in if those styles are inherited.

Here's an example.

import { html, css, LitElement } from 'lit';
import { customElement, property } from 'lit/decorators.js';

@customElement('simple-greeting')
export class SimpleGreeting extends LitElement {
  static styles = css``;

  @property()
  name = 'Somebody';

  render() {
    return html`<p>Hello, ${this.name}!</p>`;
  }
}
Enter fullscreen mode Exit fullscreen mode
<div style="color: red;">
  <simple-greeting name="World"></simple-greeting>
</div>
Enter fullscreen mode Exit fullscreen mode

The text color is applied outside of the web component in the light dom but since color is an inherited css property the text inside the component's shadow dom will also inherit that color. Now this just an example of text color but there's many more inherited css properties. Here's a list of the common ones.

4. Utility Classes Limitations

Previously we talked about how the shadow dom prevents styles from the light dom targeting elements within the shadow dom. This also means we can't use utility class frameworks like tailwindcss.

Today utility class css frameworks like tailwindcss are very popular for a good reason. I'm not going to get into that in this blog. But unfortuently in web components at least with Lit we are limited to using CSS in JS. Not only is this less productive but we also need to make sure we setup our build system to handle minifying the CSS in JS template strings. If you don't do that it'll degrade the performance of your app because it increases the JS bundle size of your app. This is the major issue that CSS in JS frameworks ran into so they had to come up with zero runtime based solutions.

5. Event Retargeting

Normally without the shadow dom you may be used to events where target is a reference to the object onto which the event was dispatched. Whereas currentTarget is the element in which the event handler is attached.
However this works differently in the shadow dom. When a composed event is emitted within the shadow dom. The event will get retargeted so the target and currentTarget will be the Lit component that has the event listener.

Here's an example.

component-b

import { html, css, LitElement } from 'lit';
import { customElement, property } from 'lit/decorators.js';

@customElement('component-b')
export class ComponentB extends LitElement {
  override render() {
    return html`<button>Click me</button>`;
  }
}
Enter fullscreen mode Exit fullscreen mode

When we click the <button> the button emits a composed event that bubbles.

component-a

import { html, css, LitElement } from 'lit';
import { customElement, property } from 'lit/decorators.js';
import './component-b.js';

@customElement('component-a')
export class ComponentA extends LitElement {
  override connectedCallback() {
    super.connectedCallback();
    this.addEventListener('click', (e) => {
      console.log(e);
    });
  }

  override render() {
    return html`<component-b></component-b>`;
  }
}
Enter fullscreen mode Exit fullscreen mode

Since the event is coming from component-b you might think that the target would be component-b or the button. However the event gets retarged so the target becomes component-a.

So if you need to know if an event came from the <button> or <component-b> you'll need to check the event's composedPath.

6. Full page reloads

If <a> links are used within the shadow dom as in this example it'll trigger a full page reload in your app.

import { html, css, LitElement } from 'lit';
import { customElement, property } from 'lit/decorators.js';

@customElement('some-link')
export class SomeLink extends LitElement {
  static styles = css``;

  @property() href = '';

  render() {
    return html`
      <a .href=${this.href}>
        <slot></slot>
      </a>
    `;
  }
}
Enter fullscreen mode Exit fullscreen mode

This is because the routing is handled by the browser not your framework. Frameworks need to intervene these events and handle the routing at the framework level. However because events are retargetted in the shadow dom this makes it more challenging for frameworks to do so since they don't have easy access to the anchor element.

To workaround this issue we can setup an event handler on the <a> that will stop propagation on the event and emit a new event. The new event will need to bubble and be composed. Also in the detail we need access
to the <a> instance which we can get from the e.currentTarget.

import { html, css, LitElement } from 'lit';
import { customElement, property } from 'lit/decorators.js';

@customElement('some-link')
export class SomeLink extends LitElement {
  static styles = css``;

  @property() href = '';

  render() {
    return html`
      <a @click=${this._handleClick} .href=${this.href}>
        <slot></slot>
      </a>
    `;
  }

  private _handleClick(e: Event) {
    e.stopPropagation();
    this.dispatchEvent(
      new CustomEvent('some-link-clicked', {
        bubbles: true,
        composed: true,
        detail: e.currentTarget,
      })
    );
  }
}
Enter fullscreen mode Exit fullscreen mode

On the consuming side you can setup a global event listener to listen for this event and handle the routing by calling framework specific routing functions.

7. Nested shadow doms

When building out web components. You can either make the decision to slot other web components or nest them inside another. Here's an example.

slotted icon

<some-banner>
  <some-icon slot="icon" icon-name="my-icon"></some-icon>
</some-banner>
Enter fullscreen mode Exit fullscreen mode

nested icon

<some-banner icon-name="my-icon"></some-banner>
Enter fullscreen mode Exit fullscreen mode

If you decide to nest the component this can make it more difficult to query the nested components. Especially if you have a QA team that needs to create end to end tests, since they'll need to target specific elements on the page.
For example to access some-icon we need to first access some-banner by grabbing it's shadowRoot then create a new query inside that shadow root.

someBannerEl.shadowRoot?.queryElement('some-icon');
Enter fullscreen mode Exit fullscreen mode

This may look simple but it gets increasingly more difficult the more deeply nested your components are. Also if your components are nested this can make working with tooltips more difficult. Especially if you need to target a deeply nested element so you can show the tooltip underneath it.

What I've found is that using slots makes our components smaller and more flexible which is also more maintainable. So prefer slots, avoid nesting shadow doms.

8. Limited ::slotted Selector

Slots provide a way to compose UI elements, but they have limitations in web components.

The ::slotted selector only applies to the direct children of a slot, limiting its usefulness in more complex scenarios.

Here's an example.

/* ✅ works */
::slotted(.first) {
  background: red;
}

/* ❌ does not work */
::slotted(.second) {
  background: orange;
}
Enter fullscreen mode Exit fullscreen mode
<some-component>
  <div class="first">
    First
    <div class="second">Second</div>
  </div>
  <div class="first">First</div>
</some-component>
Enter fullscreen mode Exit fullscreen mode

Here using ::slotted you can only target the div that is the direct child (the div with class .first). In web components this is by design for performance reasons
but something to keep in mind. I often see this as a gotcha when devs first work with web components.

9. Slotted elements are always in the dom

Web components use <slot> to render the children. However, the children will always be in the dom regardless if <slot> is present or not.

By keeping the children in the dom this can create an unwanted behavior where state can persist after the content is reshown again.

A common scenario is placing an <input> inside a modal. We usually don't expect the input to keep its state when the modal closes and reopens again. (See example)

import { html, css, LitElement, nothing } from 'lit';
import { customElement, property, state } from 'lit/decorators.js';

@customElement('some-component')
export class SomeComponent extends LitElement {
  @state()
  private _isOpen = true;

  render() {
    return html`
      <button @click=${this._toggle}>${this._isOpen ? 'Close' : 'Open'}</button>
      ${this._isOpen ? html`<slot></slot>` : nothing}
    `;
  }

  private _toggle() {
    this._isOpen = !this._isOpen;
  }
}
Enter fullscreen mode Exit fullscreen mode
<!DOCTYPE html>
<head>
  <script type="module" src="./some-component.js"></script>
</head>
<body>
  <some-component>
    <input placeholder="Type here" />
  </some-component>
</body>
Enter fullscreen mode Exit fullscreen mode

10. Slower Feature Adoption

Web components often lag behind popular frameworks like Vue, React, Svelte and Solid in adopting new features and best practices.
This can be due to the fact that web components rely on browser implementations and standards, which can take longer to evolve compared to the rapid development cycles of modern JavaScript frameworks.
As a result, developers might find themselves waiting for certain capabilities or having to implement workarounds that are readily available in other frameworks.

Some examples of this is Lit using CSS in JS as a default option for styling. It's been known for a long time now that CSS in JS frameworks had performance issues
because they often introduced additional runtime overhead. So we started seeing newer CSS in JS frameworks that switched to a zero runtime based solutions.
Lit's CSS in JS solution is still runtime based.

Another example is with Signals. Currently the default behavior in Lit is that we add reactivity to class properties by adding the @property decorator.
However, when the property gets changed it'll trigger the entire component to re-render. With Signals only part of the component that relies on the signal will get updated.
This is more efficient for working with UIs. So efficient that there's a new proposal (TC39) to get this added to JavaScript.
Now Lit does provide a package to use Signals but it's not the default reactivity when other frameworks like Vue and Solid have already been doing this for years.
We most likely won't see Signals as the default reactivity for a few more years until signals are apart of the web standards.

Yet another example which relates to my previous caveat "9. Slotted elements are always in the dom". Rich Harris the creator of Svelte talked about this
in his blog post 5 years ago titled "Why I don't use Web Components".
He talks about how they adopted the web standards approach for how slotted content renders eagerly in Svelte v2. However, they had to move away from it
in Svelte 3 because it was such a big point of frustration for developers. They noticed that majority of the time you want the slotted content to render lazily.

I can come up with more examples such as in web components there's no easy way to pass data to slots when other frameworks like Vuejs already has support for this. But the main takeaway here is that
web components since they rely on web standards adopts features much slower than frameworks that do not rely on web standards.
By not relying on web standards we can innovate and come up with better solutions.

Conclusion

Web Components offer a powerful way to create reusable and encapsulated custom elements. However, as we've explored, there are several caveats and challenges that developers may face when working with them. Such as framework incompatibility, usage in micro frontends, limitations of the Shadow DOM, issues with event retargeting, slots, and slow feature adoption are all areas that require careful consideration.

Despite these challenges, the benefits of Web Components, such as true encapsulation, portability, and framework independence, make them a valuable tool in modern web development. As the ecosystem continues to evolve, we can expect to see improvements and new solutions that address these caveats.

For developers considering Web Components, it's essential to weigh these pros and cons and stay informed about the latest advancements in the field. With the right approach and understanding, Web Components can be a powerful addition to your development toolkit.

Top comments (0)