Something that has always bothered me as a front-ender is all the crazy things we do to scope our CSS. Whether it’s naming conventions like BEM, hashing classes via CSS Modules, or inlining them with tools like Styled-Components, I’ve never been thrilled with the solution. In fact, that’s what made me hope web components would happen sooner. Unfortunately I never had the chance to use it professionally, and frankly, support wasn’t there. But oh how things have changed.

So the other day I was getting ready to do a talk for Front End PDX. I was looking to combine the function as child element (FACE) pattern, aka renderProps, with an es6'ish compose. It didn’t work out :(

However, as I was playing with the FACE pattern, I thought could I create a super tiny css-in-js solution with Shadow Dom. How hard could it be? Turns out not really, just 48 lines of code.

Any child element wrapped by a ShadowDom component will be appended to its ShadowRoot.

Any component passed to the lightDom will be placed in the components light DOM and won’t appear unless you’ve slotted it and declared a slot in the ShadowDom component.

Styling the ShadowDom is old school. Just a plain old style tag and BAM, we’ve got a working react component with encapsulated styles, markup, and full access to the lifecycle methods.

The only caveat is testing. JSDOM doesn’t have a clue what to do with attachShadow, and I honestly gave up after a few hours of trying to make it understand. I don’t plan on ever using this component, but I figured I’d share it in case someone would like to give it a shot.

Repo: https://github.com/EdwardIrby/react-shadow-dom-component

Live version: https://absorbed-pump.glitch.me/