search
HomeWeb Front-endJS TutorialCaveats You May Face While Working With Web Components

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 {}

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></some-web-component>
})
export class SomeWebComponentWrapper {
  @Input() someClassProperty: string;
}

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

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',
  },
});

Usage

<myelementcomponent active="{isActive}" onactivate="{(e)"> setIsActive(e.active)}
  onchange={handleChange}
/>
</myelementcomponent>

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.

@NgModule({
  schemas: [CUSTOM_ELEMENTS_SCHEMA],
})
export class MyModule {}

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

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

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

After

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',
  },
});

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

<myelementcomponent active="{isActive}" onactivate="{(e)"> setIsActive(e.active)}
  onchange={handleChange}
/>
</myelementcomponent>

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

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

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.

@customElement('simple-greeting')
export class SimpleGreeting extends LitElement {
  render() {
    return html`<p>Hello world!</p>`;
  }
}
export class SimpleGreeting extends LitElement {
  static tagName = 'simple-greeting';

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

When we click the

component-a

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

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

6. Full page reloads

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

@NgModule({
  schemas: [CUSTOM_ELEMENTS_SCHEMA],
})
export class MyModule {}

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 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
instance which we can get from the e.currentTarget.

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

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

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

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',
  },
});

nested icon

<myelementcomponent active="{isActive}" onactivate="{(e)"> setIsActive(e.active)}
  onchange={handleChange}
/>
</myelementcomponent>

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.

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

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.

@customElement('simple-greeting')
export class SimpleGreeting extends LitElement {
  render() {
    return html`<p>Hello world!</p>`;
  }
}
export class SimpleGreeting extends LitElement {
  static tagName = 'simple-greeting';

  render() {
    return html`<p>Hello world!</p>`;
  }
}
[SimpleGreeting].forEach((component) => {
  const newTag = `app1-${component.tagName}`;
  if (!customElements.get(newTag)) {
    customElements.define(newTag, SimpleGreeting);
  }
});

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.

The above is the detailed content of Caveats You May Face While Working With Web Components. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
The Future of Python and JavaScript: Trends and PredictionsThe Future of Python and JavaScript: Trends and PredictionsApr 27, 2025 am 12:21 AM

The future trends of Python and JavaScript include: 1. Python will consolidate its position in the fields of scientific computing and AI, 2. JavaScript will promote the development of web technology, 3. Cross-platform development will become a hot topic, and 4. Performance optimization will be the focus. Both will continue to expand application scenarios in their respective fields and make more breakthroughs in performance.

Python vs. JavaScript: Development Environments and ToolsPython vs. JavaScript: Development Environments and ToolsApr 26, 2025 am 12:09 AM

Both Python and JavaScript's choices in development environments are important. 1) Python's development environment includes PyCharm, JupyterNotebook and Anaconda, which are suitable for data science and rapid prototyping. 2) The development environment of JavaScript includes Node.js, VSCode and Webpack, which are suitable for front-end and back-end development. Choosing the right tools according to project needs can improve development efficiency and project success rate.

Is JavaScript Written in C? Examining the EvidenceIs JavaScript Written in C? Examining the EvidenceApr 25, 2025 am 12:15 AM

Yes, the engine core of JavaScript is written in C. 1) The C language provides efficient performance and underlying control, which is suitable for the development of JavaScript engine. 2) Taking the V8 engine as an example, its core is written in C, combining the efficiency and object-oriented characteristics of C. 3) The working principle of the JavaScript engine includes parsing, compiling and execution, and the C language plays a key role in these processes.

JavaScript's Role: Making the Web Interactive and DynamicJavaScript's Role: Making the Web Interactive and DynamicApr 24, 2025 am 12:12 AM

JavaScript is at the heart of modern websites because it enhances the interactivity and dynamicity of web pages. 1) It allows to change content without refreshing the page, 2) manipulate web pages through DOMAPI, 3) support complex interactive effects such as animation and drag-and-drop, 4) optimize performance and best practices to improve user experience.

C   and JavaScript: The Connection ExplainedC and JavaScript: The Connection ExplainedApr 23, 2025 am 12:07 AM

C and JavaScript achieve interoperability through WebAssembly. 1) C code is compiled into WebAssembly module and introduced into JavaScript environment to enhance computing power. 2) In game development, C handles physics engines and graphics rendering, and JavaScript is responsible for game logic and user interface.

From Websites to Apps: The Diverse Applications of JavaScriptFrom Websites to Apps: The Diverse Applications of JavaScriptApr 22, 2025 am 12:02 AM

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python vs. JavaScript: Use Cases and Applications ComparedPython vs. JavaScript: Use Cases and Applications ComparedApr 21, 2025 am 12:01 AM

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

The Role of C/C   in JavaScript Interpreters and CompilersThe Role of C/C in JavaScript Interpreters and CompilersApr 20, 2025 am 12:01 AM

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool