Blackbox Components

Blackbox components are the simplest way to integrate D3 and React. You can think of them as wrappers around D3 visualizations.

You can take any D3 example from the internets or your brain, wrap it in a thin React component, and it Just Works™. Yes, we go against what I just said and let D3 control a small part of the DOM tree.

We throw away most of React’s power, but we gain a quick way to get things working.

I call the approach “blackbox” because React’s engine can’t see inside your component, can’t help with rendering, and has no idea what’s going on. From this point onward in the DOM tree, you are on your own. It sounds scary, but it’s okay if you’re careful.

Here’s how it works:

  • React renders an anchor element
  • D3 hijacks it and puts stuff in

You have to manually re-render on props and state changes. You’re also throwing away and recreating your component’s entire DOM on each re-render.

Manual re-rendering is not as annoying as it sounds, but the inefficiency can get pretty bad with complex visualizations. Use this technique sparingly.

A quick blackbox example - a D3 axis

Let’s build an axis component. Axes are the perfect use-case for blackbox components. D3 comes with an axis generator bundled inside, and they’re difficult to build from scratch.

They don’t look difficult, but there are many tiny details you have to get just right.

D3’s axis generator takes a scale and some configuration to render an axis for us. The code looks like this:

Create a free account to view this lesson.

By signing up, you agree to Educative's Terms of Service and Privacy Policy