Take any D3 example you find in the wild and wrap it in a React component. Great for quick experiments and meeting deadlines. 😛
Check out how it works in a live Codesandbox
- Install
d3blackbox
with npm
$ npm install -s d3blackbox
- Find a D3 example you like
- Copy its code, put it in a function
- Wrap function in
D3blackbox
import React from "react";
import D3blackbox from "d3blackbox";
import * as d3 from "d3";
const MyDataviz = D3blackbox(function(anchor, props, state) {
const svg = d3.select(anchor.current);
// the rest of your D3 code
});
export default MyDataviz;
- Render inside an
<svg></svg>
element - Enjoy your blackbox D3 component
D3blackbox renders an anchor element and delegates control to your render function. You get an anchor
ref, the component's props
, and state
. Do what you want :)
Great for meeting deadlines and playing around with other people's code. Not recommended for large scale use due to performance constraints. Your render function runs on every component update and redraws the entire DOM subtree. React's rendering engine can't help you.
That's why it's called a sandbox.
That's okay. D3blackbox
lets you delegate control to any rendering library you want. As long as you're okay rendering into a <g></g>
element.
You can even use this approach to render Vue apps inside your React apps. 🤨
That's okay you weirdo. Use the component
argument to specify a different component.
render() {
return <MyDataviz component="div" />
}
Yes. Hooks are alpha support and all that, but here's how you can use D3 blackbox as a React hook.
import { useD3 } from "d3blackbox";
function renderSomeD3(anchor) {
d3.select(anchor);
// ...
}
const MyD3Component = ({ x, y }) => {
const refAnchor = useD3(anchor => renderSomeD3(anchor));
return <g ref={refAnchor} transform={`translate(${x}, ${y})`} />;
};
Built with love by Swizec
Cheers
Only took me 2 years to get around to opensourcing this 😅