Swizec Teller - a geek with a hatswizec.com

Senior Mindset Book

Get promoted, earn a bigger salary, work for top companies

Senior Engineer Mindset cover
Learn more

    Getting the CSS out of rendered React components

    Here's a fun problem for ya: How do you get the CSS from a rendered React component?

    Right-click, inspect element, see it in dev tools. D'oh ๐Ÿ™„

    What about programmatically?

    thinking giphy

    Turns out that's not so easy.

    You could, for example, try the window.getComputedStyle method. Same as that DevTools view with all the styles.

    But that's too much stuff. You get values for every CSS property that exists in the spec. ๐Ÿ˜…

    What else can you try?

    Well there's always the style prop. You could get its value and hope for the best.

    But that only works if you're actually using it. Most people these days do not. Sure it's plenty useful for one-off overrides, but when was the last time you saw a project that heavily relies on the style prop?

    Exactly. Not in a while.

    Most projects have settled on styled-components or CSS modules. That makes our job both easier and harder. ๐Ÿคจ

    Getting CSS from styled-components

    You can watch me figure this one out in a livestream ๐Ÿ‘‡

    I tried all of the above and then some. Here's the solution I came up with: ๐Ÿ‘จโ€๐ŸŽจ component-css-extractor. Open sourced for your ease of use ๐Ÿ˜Š

    CodeSandbox to prove it works ๐Ÿ‘‡

    ๐Ÿ‘จโ€๐ŸŽจ component-css-extractor relies on the fact that both styled-components and CSS modules use class names.

    Each styled component that you write is assigned a unique class name. Rendered components get the class property, CSS rules go in a <style> tag in your header.

    We can combine those to get a clean set of CSS rules. Scoped to the target component with nothing extra to mess us up. ๐Ÿ‘Œ

    34 lines of prettified code in total ๐Ÿ‘‡

    Click through for source
    Click through for source

    As the comments say:

    1. Collect class names for entire subtree
    2. Use document.head.getElementsByTagName("style") to get all <style> tags
    3. Use the css module to parse collected CSS into a JavaScript object
    4. Filter rules that don't apply to our classes
    5. Stringify and return

    Works like a charm ๐Ÿ‘จโ€๐ŸŽจ

    magic giphy

    Some caveats

    As always there are some limitations.

    First of all, this won't work on the server or during build time. Collecting <style> tags requires access to the DOM as it exists in the browser. You don't have that during server-side-rendering, I think.

    Fortunately you don't need ๐Ÿ‘จโ€๐ŸŽจ component-css-extractor on the server. Styled-components has a built-in way of extracting styles into a string for serving to the client.

    The built-in way doesn't work in the browser, hence why I went down this rabbit hole.

    Second of all, if you have global stylesheets in a .css file, ๐Ÿ‘จโ€๐ŸŽจ component-css-extractor won't pick those up. Makes the code simpler.

    Imagine having to parse all of CSS in all your stylesheets and figuring out what does and doesn't apply to a particular DOM node. Might as well build a browser rendering engine lol.

    Happy Monday, ~Swizec

    Published on June 3rd, 2019 in Front End, Technical

    Did you enjoy this article?

    Continue reading about Getting the CSS out of rendered React components

    Semantically similar articles hand-picked by GPT-4

    Senior Mindset Book

    Get promoted, earn a bigger salary, work for top companies

    Learn more

    Have a burning question that you think I can answer? Hit me up on twitter and I'll do my best.

    Who am I and who do I help? I'm Swizec Teller and I turn coders into engineers with "Raw and honest from the heart!" writing. No bullshit. Real insights into the career and skills of a modern software engineer.

    Want to become a true senior engineer? Take ownership, have autonomy, and be a force multiplier on your team. The Senior Engineer Mindset ebook can help ๐Ÿ‘‰ swizec.com/senior-mindset. These are the shifts in mindset that unlocked my career.

    Curious about Serverless and the modern backend? Check out Serverless Handbook, for frontend engineers ๐Ÿ‘‰ ServerlessHandbook.dev

    Want to Stop copy pasting D3 examples and create data visualizations of your own? Learn how to build scalable dataviz React components your whole team can understand with React for Data Visualization

    Want to get my best emails on JavaScript, React, Serverless, Fullstack Web, or Indie Hacking? Check out swizec.com/collections

    Did someone amazing share this letter with you? Wonderful! You can sign up for my weekly letters for software engineers on their path to greatness, here: swizec.com/blog

    Want to brush up on your modern JavaScript syntax? Check out my interactive cheatsheet: es6cheatsheet.com

    By the way, just in case no one has told you it yet today: I love and appreciate you for who you are โค๏ธ

    Created by Swizec with โค๏ธ