How to generate client side svg with d3 without binding to DOM (using with React.js)

I am using React.js to create an application that includes quite a few svg diagrams. I use d3 functions that help in creating diagrams such as scales, but then using React to generate svg elements. Here is a great response to the approach: http://10consulting.com/2014/02/19/d3-plus-reactjs-for-charting/

Part of why I walked this road was for performance - the first version of the application was too slow. It has many elements and a lot of user interactivity, all on the client side. I am trying to basically recreate the dc.js library in React.

This is a really fun approach and intuitive (more than d3 one IMO). However, building axes are tiring, and d3 does it so well. I would like d3 to just be able to output a string of svg elements that represent the axis (and possibly other elements), and I pass it to React for inclusion in the DOM.

I saw this SO question ( How to make d3.js generate SVG without drawing it? ), And the answer was to add it to the DOM and delete or create a DOM fragment. These approaches run counter to the React approach and are likely to deny the benefits of React. I also saw jsdom and phantomjs solutions that won't work in my case.

Can d3 generate svg without adding it to the DOM?

+7
reactjs svg
source share
2 answers

Not. D3 by design runs directly on the DOM of its choice. To instead generate string representations without changing the DOM, you will need to change its source code (and this will be a fairly significant modification).

+2
source share

@Lars is correct if you use traditional means. However, this is definitely possible with jsdom '. This library can mimic the DOM, and also allows you to enter lines. This means that you can enter the root element in a fake DOM and get a new window element to control. Then you can use D3 without changing its source, and use as usual.

This would allow the generation of SVG.

+2
source share

All Articles