Swizec Teller - a geek with a hatswizec.com

    Easy D3 blackbox components with React hooks

    What if you could take any random D3 example and wrap it in a React component in just 2 minutes? Wouldn't that be great? 👌

    Combining D3 and React can be tricky. D3 loves internal state, React likes components to be stateless. I wrote a whole book about it there's so much nuance.

    "Fully controlled components" is the latest buzzword I believe. Rendering depends on props.

    D3 likes to set up objects with internal state. You call them and out comes a beautiful picture. A data visualization. A piece of art. Anything really it's very flexible.

    Something like this for example 👇

    No, I don't know how that example works. And that's the point.

    Most people write D3 by looking for examples, copy-pasting some code, and tweaking until it looks right.

    But most D3 examples out there are written as one-off pieces of art. With flat JavaScript, old conventions, and code that's not very reusable.

    React doesn't like that.

    D3 blackbox components

    Enter blackbox components: A quick way to wrap any D3 example in a React component.

    Here's an old video of mine explaining how that works 👇

    The approach works like this:

    1. Find example you like
    2. Copy the code
    3. Wrap it in a render function
    4. Use a D3blackbox higher order component to render an anchor element
    5. Use mount and update hooks to render D3 into the anchor
    6. React controls the anchor element, D3 controls the insides

    This is a quick way to integrate any D3 example in your React code. Fast to set up, easy to work with.

    Here's a CodeSandbox from my workshops using the blackbox approach to make a random barchart reusable.

    👌

    The HOC to make that work is a little scary. Hard to explain too.

    export default function D3blackbox(D3render) {
    return class Blackbox extends React.Component {
    anchor = React.createRef();
    componentDidMount() {
    D3render(this.anchor, this.props, this.state);
    }
    componentDidUpdate() {
    D3render(this.anchor, this.props, this.state);
    }
    render() {
    const { x, y } = this.props;
    return <g transform="{`translate(${x}," ${y})`}="" ref={this.anchor}>;
    }
    };
    }
    </g>

    17 sloc function that returns a class-based component with an anchor, two lifecycle methods, and a rendered ``element. That's our anchor.

    Using this HOC looks like wrapping some D3 code in a D3blackbox call.

    const Barchart = D3blackbox(function(anchor, props) {
    var svg = d3.select(anchor.current),
    // ...

    Your D3 code gets the anchor, props, and state. Do what you want.

    Hooks make blackboxes easier

    That's all fine and good, but we can make it even better with React's new hooks proposal. Hooks are an early RFC, and as of November 2018, this API is still likely to change.

    But you can try them out with React 16.7 alpha. Just set your package.json to next.

    Using the same idea:

    1. React controls anchor node
    2. D3 controls the insides
    3. Render D3 on all updates
    4. Wrap D3 in React super fast

    Hooks let us achieve all that in just 8 lines of code. Versus the 17 it took with a HOC.

    Here's me figuring it out in a ninja livecode session 👇

    And here's proof that it takes just 2 minutes to take any random D3 example and wrap it in a React component. Whole video fits in a tweet 👇

    https://twitter.com/Swizec/status/1057519327774232576

    Here's how it works:

    const D3blackbox = ({ x, y, render }) => {
    const refAnchor = React.useRef(null);
    React.useEffect(() => {
    render(d3.select(refAnchor.current));
    });
    return <g ref={refAnchor} transform="{`translate(${x}," ${y})`}="">;
    };
    </g>

    We have a D3blackbox component that takes coordinates and a render method as props. It uses the useRef hook to add a React ref to our functional component and useEffect to automatically call your render method on component mount and update.

    It passes a d3.select-ed element into your render method so you can get started with D3 stuff right away.

    Then it renders the anchor element as an SVG group.

    You use it like this:

    <d3blackbox x={0} y={400} render="{svg" ==""> // D3 code} />
    </d3blackbox>

    😍

    Caveats

    Hooks themselves aren't really ready for realzies quite yet. You can play around, but I don't recommend using in production just yet or rewriting your apps.

    React ecosystem sure seems excited though. That genie is never going back in its bottle.

    D3 blackbox rendering itself has a few caveats. You're destroying and reconstructing your entire D3 visualization on every update. This can become costly.

    Once you take control away from React, its beautiful algorithms and optimizations can't help you.

    Quick prototypes and experiments, though, this is perfect 👍🏼

    Did you enjoy this article?

    Published on November 1st, 2018 in Front End, Technical,

    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 15,161+ engineers just like you already growing their careers with my emails, workshops, books, and courses.

    ⭐️⭐️⭐️⭐️✨
    4.5 stars average rating

    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

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

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