Hacker News new | ask | show | jobs
by tompark 1502 days ago
YES! I liked React components too but wanted something simpler so on my current project I've been using native browser Web Components/Custom Elements without any framework -- in fact, my project has zero dependencies on the client-side. It does need a few globally installed modules (typescript, webpack/webpack-cli, nodemon).

Requiring that javascript is enabled in the browser isn't a factor because my project relies on WebRTC, which requires javascript anyway. Its main value prop wouldn't exist with javascript disabled, so I'm just going to ignore that criticism.

To work across Chrome/Firefox/Safari, I avoided templates/slots by attaching the `ShadowRoot` and setting its `.innerHTML` to the result of a function that returns the html template literal string (where the function can fill variables in that string). I haven't tested this on Edge, but it works fine natively on the other browsers without any polyfills.

I love using Typescript without any client-side framework, but you might have different constraints than I do. Particularly when it comes to job search -- it seems that almost any front-end webdev position requires React/Angular/etc so you might find that it's a career-limiting move to go straight to plain Web Components as I did. I don't care because my main background is in mobile not web.

1 comments

Oh BTW, if you do this, there is one nasty Safari bug I ran into which needed a simple workaround. If you have many copies of a particular component on a page, and that web component uses SVG, then the elements within the SVG need to have unique IDs. This is a Safari-only bug that's related to SVG, not the web component API.

For example, say you use a svg button component several times on a page, and there's a filter in the SVG that you use to change the appearance of the button when it's disabled. If the filter tag doesn't have a unique ID, and one of the buttons is disabled while all the other buttons are enabled, then all the buttons will become disabled if you modify just one of them, because they're all referencing the same filter.

It's very easy to make the IDs unique by using a sequence number (as a member of the component class), incrementing the sequence number in the component constructor, and appending that sequence number to the ID every time you call the template function.

After I fixed this problem in my code, I found out that the css-tricks guy had also run into it and he did a whole write-up about it, but he was using React not Web Components: https://css-tricks.com/heres-how-i-solved-a-weird-bug-using-...