Swizec Teller - a geek with a hatswizec.com

    Hacking the React AST for fun and profit – #CodeWithSwiz ep34

    This is hold my beer level of hackery. It didn't work but we learned lots in the process.

    CodeWithSwiz is a weekly live show. Like a podcast with video and fun hacking. Focused on experiments and open source. Join live most Tuesday mornings

    The problem

    On ServerlessHandbook.dev there is a paywall. Every visitor can read the first 30% of every chapter. To read more you have to buy the book or unlock specific chapters with an email.

    This works.

    But it doesn't look good. Content's not styled.

    You're supposed to see this:

    Current working solution

    You get unstyled content because of how the paywall works.

    // rendering the main content
    contentUnlocked ? (
    <main id="content">{props.children}</main>
    ) : (
    <main id="content">

    If content unlocked, show content. If content locked, snip.

    The snipping is a hack:

    export function SnipContent({ children }) {
    const html = ReactDOMServer.renderToString(children).split(
    '<div id="lock"></div>'
    return <div dangerouslySetInnerHTML={{ __html: html }} />

    Take the children, render to a string, split by the lock, take first part, render back out as HTML.

    When this happens, we throw out all the styling machinery. ThemeUI doesn't see these components, doesn't add CSS classes.

    Wrapping in ThemeUI's root wrapper doesn't work either. It's a CSS-in-JS library and doesn't add global tag-based styling. Needs to see the details.

    Attempt 1: Hack React's AST

    We have those ThemeUI classes – they're in the children prop!

    What children looks like
    What children looks like

    The children prop is a portion of React's AST. An abstract syntax tree that represents the data structure of your React app. React uses this to run DOM events, deal with effects, and render.

    Our content hides in the type: MDXContent node. We weren't able to dig into that.

    For a brief moment it looked like we might be able to hack React's Fiber implementation, but that was too much. If I understand correctly, fibers are the syntax tree that React uses, but they're based on functions calling functions. Not a hackable data structure.

    React Fibers of our content
    React Fibers of our content

    Attempt 2: Render to HTML, parse back to JSX

    Next idea 👉 what if we render to HTML, snip the content, parse back to JSX, and pass that back to the main rendering machine?

    import parseToReact from "html-react-parser"
    // ...
    const html = ReactDOMServer.renderToString(children).split(
    '<div id="lock"></div>'
    const snippedChildren = parseToReact(html)
    return snippedChildren

    html-react-parser is a library that takes any HTML and parses it to a JSX string.

    And it worked! We got an understandable data structure of our content 🥳

    Snipped content after JSX parsing
    Snipped content after JSX parsing

    You can look at that and understand what's going on! React components have normal types, there's props, it all makes sense.

    Except it doesn't style. ThemeUI doesn't run through these, doesn't add CSS props, doesn't do squat. 🥲

    Attempt 3: Render as MDX

    What if you took the HTML or the parsed JSX and shoved that in a MDX renderer yourself?

    import { MDXProvider } from "@mdx-js/react"
    import { MDXRenderer } from "gatsby-plugin-mdx"
    // ...
    return (
    {snippedChildren} // or {html}

    Cryptic error from the bowels of Gatsby. Something undefined.

    MDXProvider specifies components for MDX. Where the styling and any custom machinery hooks into.

    MDXRenderer takes a compiled MDX source and renders it as React.

    And that's the rub 👉 compiled MDX source. We don't have that. We have random HTML or React components. MDX chokes and dies.

    You could compile with mdx(data) from the @mdx-js/mdx package, but that depends on Node.js libraries that don't work inside React components. You have to guarantee running on the server.

    Including the full MDX runtime in your client code would work ... and destroy your Lighthouse scores. It's a big pile of code.

    What I feared: The real solution

    We're going to need a real solution – an MDX/Remark plugin that knows how to grab the snipped content from our data source. 💩

    Next time!


    Did you enjoy this article?

    Published on June 29th, 2021 in React, Livecoding, CodeWithSwiz, Gatsby

    Learned something new?
    Want to become an expert?

    Here's how it works 👇

    Leave your email and I'll send you thoughtfully written emails every week about React, JavaScript, and your career. Lessons learned over 20 years in the industry working with companies ranging from tiny startups to Fortune5 behemoths.

    Join Swizec's Newsletter

    And get thoughtful letters 💌 on mindsets, tactics, and technical skills for your career. Real lessons from building production software. No bullshit.

    "Man, love your simple writing! Yours is the only newsletter I open and only blog that I give a fuck to read & scroll till the end. And wow always take away lessons with me. Inspiring! And very relatable. 👌"

    ~ Ashish Kumar

    Join over 14,000 engineers just like you already improving their careers with my letters, workshops, courses, and talks. ✌️

    Have a burning question that you think I can answer? I don't have all of the answers, but I have some! Hit me up on twitter or book a 30min ama for in-depth help.

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

    Curious about Serverless and the modern backend? Check out Serverless Handbook, modern backend for the frontend engineer.

    Ready to learn how it all fits together and build a modern webapp from scratch? Learn how to launch a webapp and make your first 💰 on the side with ServerlessReact.Dev

    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 ❤️