react-d3-unmanaged-wrapper
React component that uses Mike Bostock's reusable charts pattern
to render d3 code inside a <svg>
or <div>
container. The DOM elements created
with d3 are unmanaged: the React component is unaware of the contents of the
container and will not touch those elements.
Example
Create your d3 drawing code following the reusable charts
pattern. For example, create a file ./d3fn.js
:
/** * Follow Mike Bostock's "reusable charts" pattern returning a closure * to (re-)draw the d3 content. * * The outer function sets up private variables like width, height, etc. * and returns the inner function (closure) to draw and update the chart. * * @return * drawing and updating of the chart. */const d3fn = { // --- define private variables let width; let height; // --- set up one-time elements like scales here... /** * The inner function generates and updates the chart. * * @param selection */ { selection; }; // --- getter-setter functions here inner { if !argumentslength return width; width = value; return inner; }; inner { if !argumentslength return height; height = value; return inner; }; return inner;} moduleexports = d3fn;
Now set up and render the D3 component, e.g. in ./index.js
:
const ReactDOM = ;const D3Component = ;const d3fn = ; const options = width: 800 height: 200 renderMode: 'svg' d3fn: d3fn data: 14 19 25 6 9 24 31; // instantiate component and pass in width, height, data and d3 functionconst chart = <D3Component ...options />; // render in DOM (or embed in other components)ReactDOM;
React and D3
There are several different ways to combine d3 and React code. The issue is that they both manipulate the DOM in different ways. React uses a virtual DOM, and an efficient diff-ing algorithm, and updates only the DOM nodes that actually need to change. d3 accesses the DOM directly, and through data binding updates the DOM nodes that have been modified.
The approach taken here is quite simple. React sets up (and "owns") the container
but considers the elements inside the container unmanaged and leaves their
handling to d3. This is achieved by calling the d3 drawing function on
componentDidMount
(for initial setup) and componentDidUpdate
(for redrawing).
License
Apache 2.0