Web Components Eliminate JavaScript Framework Lock-in

Jake Lazaroff November 27, 2023
Source
We've seen a lot of great posts about web components lately. Many have focused on the burgeoning HTML web components pattern, which eschews shadow DOM in favor of progressively enhancing existing markup. There's also been discussion — including this post by yours truly — about fully replacing JavaScript frameworks with web components. Those aren't the only options, though. You can also use web components in tandem with JavaScript frameworks. To that end, I want to talk about a key benefit that I haven't seen mentioned as much: web components can dramatically loosen the coupling of JavaScript frameworks. To prove it, we're going to do something kinda crazy: build an app where every single component is written with a different framework. It probably goes without saying that you should not build a real app like this! But there are valid reasons for mixing frameworks. Maybe you're gradually migrating from React to Vue. Maybe your app is built with Solid, but you want to use a third-party library that only exists as an Angular component. Maybe you want to use Svelte for a few "islands of interactivity" in an otherwise static website. Here's what we're going to create: a simple little todo app based loosely on TodoMVC. As we build it, we'll see how web components can encapsulate JavaScript frameworks, allowing us to use them without imposing broader constraints on the rest of the application. What's a Web Component? In case you're not familiar with web components, here's a brief primer on how they work. First, we declare a subclass of HTMLElement in JavaScript. Let's call it MyComponent: That call to attachShadow in the constructor makes our component use the shadow DOM, which encapsulates the markup and styles inside our component from the rest of the page. connectedCallback is called when the web component is actually connected to the DOM tree, rendering the HTML contents into the component's "shadow root". This foreshadows how we'll make our frameworks work with web components. We normally "attach" frameworks to a DOM element, and let the framework take over all descendants of that element. With web components, we can attach the framework to the shadow root, which ensures that it can only access the component's "shadow tree". Next, we define a custom element name for our MyComponent class: Whenever a tag with that custom element name appears on the page, the corresponding DOM node is actually an instance of MyComponent! Check it out: There's more to web components, but that's enough to get you through the rest of the article. Scaffolding Layout The entrypoint of our app will be a React component. Here's our humble start: We could start adding elements here to block out the basic DOM structure, but I want to write another component for that to show how we can nest web components in the same way we nest framework components. Most frameworks support composition via nesting like normal HTML elements. From the outside, it usually looks something like this: On the inside, there are a few ways that frameworks handle this. For example, React and Solid give you access to those children as a special children prop: With web components that use shadow DOM, we can do the same thing using the element. When the browser encounters a , it replaces it with the children of the web component. is actually more powerful than React or Solid's children. If we give each slot a name attribute, a web component can have multiple s, and we can determine where each nested element goes by giving it a slot attribute matching the 's name. Let's see what this looks like in practice. We'll write our layout component using Solid: There are two parts to our Solid web component: the web component wrapper at the top, and the actual Solid component at the bottom. The most important thing to notice about the Solid component is that we're using named s instead of the children prop. Whereas children is handled by Solid and would only let us nest other Solid components, s are handled by the browser itself and will let us nest any HTML element — including web components written with other frameworks! The web component wrapper is pretty similar to the example above. It creates a shadow root in the constructor, and then renders the Solid component into it in the connectedCallback method. Note that this is not a complete implementation of the web component wrapper! At the very least, we'd probably want to define an attributeChangedCallback method so we can re-render the Solid component when the attributes change. If you're using this in production, you should probably use a package Solid provides called Solid Element that handles all this for you. Back in our React app, we can now use our TodoLayout component: Note that we don't need to import anything from TodoLayout.jsx — we just use the custom element tag that we defined. Check it out: That's a React component rendering a Solid component, which takes a nested React element as a child. Adding Todos For the todo input, we'll peel the onion back a bit further and write it with no framework at all! Between this, the example web component and our Solid layout, you're probably noticing a pattern: attach a shadow root and then render some HTML inside it. Whether we hand-write the HTML or use a framework to generate it, the process is roughly the same. Here, we're using a custom event to communicate with the parent component. When the form is submitted, we dispatch an add event with the input text. Event queues are often used to decouple communication between components of a software system. Browsers lean heavily on events, and custom events in particular are an important tool in the web components toolbox — especially so because the custom element acts as a natural event bus that can be accessed from outside the web component. Before we can continue adding components, we need to figure out how to handle our state. For now, we'll just keep it in our React TodoApp component. Although we'll eventually outgrow useState, it's a perfect place to start. Each todo will have three properties: an id, a text string describing it, and a done boolean indicating whether it's been completed. We'll keep an array of our todos in React state. When we add a todo, we'll add it to the array. The one awkward part of this is that inputRef function. Our emits a custom add event when the form is submitted. Usually with React, we'd attach event listeners using props like onClick — but that only works for events that React already knows about. We need to listen for add events directly. In React Land, we use refs to directly interact with the DOM. We most commonly use them with the useRef hook, but that's not the only way! The ref prop is actually just a function that gets called with a DOM node. Rather than passing a ref returned from the useRef hook to that prop, we can instead pass a function that attaches the event listener to the DOM node directly. You might be wondering why we have to wrap the function in useCallback. The answer lies in the legacy React docs on refs (and, as far as I can tell, has not been brought over to the new docs): If the ref callback is defined as an inline function, it will get called twice during updates, first with null and then again with the DOM element. This is because a new instance of the function is created with each render, so React needs to clear the old ref and set up the new one. You can avoid this by defining the ref callback as a bound method on the class, but note that it shouldn't matter in most cases. In this case, it does matter, since we don't want to attach the event listener again on every render. So we wrap it in useCallback to ensure that we pass the same instance of the function every time. Todo Items So far, we can add todos, but not see them. The next step is writing a component to show each todo item. We'll write that component with Svelte. Svelte supports custom elements out of the box. Rather than continuing to show the same web component wrapper boilerplate every time, we'll just use that feature! Here's the code: With Svelte, the

Discussion in the ATmosphere

Loading comments...