Elf M. Sternberg

Full Stack Web Developer

Where one teaches, two learn.

Tag: #web components

To all tags

Don't use CustomEvent in Javascript. Inherit from Event Instead.

It's commonplace in Web Components to use custom events. The custom event type is an inheritor of the Event class, but it includes a new field, detail: any, that allows you to attach data to the Event, which is useful for passing data up to the listener, right?

Wrong. It's a trap. You could, theoretically, inherit from CustomEvent and narrow the content of detail to what you specifically want, and I've seen lots of code where people do exactly that.

But there's a better way: just inherit from Event. Skip the CustomEvent class and just create your own events. I'll show you how.

Web Components and CSS Libraries: An Awkward Fit

In my new job, I've been working a lot with an existing codebase that uses web components (via Lit) for the HTML and Patternfly for the CSS, and I've discovered that Patternfly, as well as other CSS Libraries such as Tailwind or Bootstrap, are awkward fits for developing web components. You usually end up importing too much per component or sacrificing code readability on the altar of code size.

Let me give you an example:

Moving From React To Lit Requires a Shift In Attitude

React is the number one most popular web application development framework, hands down, with twice the user base of its next competitor, Angular. My framework of choice is LitElement, which doesn't even appear on some of these charts.

According to Stack Overflow, 55% of developer "admire" Lit, and less than 1% get to work in it. I, fortunately, get to work in Lit, but after four years of React experience I've discovered that Lit is so very different from React, Angular, and the rest that it takes a heavy mental shift to work in it.

I work professionally on a medium-sized web application written in Lit that orchestrates and administers single-sign-on for small-to-medium businesses. I really like Lit, and working on this thing has been like being thrown into the deep end of the pool. There are two aspects of Lit that make it really different from the others and can make it hard for some developers to make the mental shift.