Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to generate svg client-side with d3 without attaching it to the DOM (using with React.js)

I'm using React.js to build an app, which includes quite a few svg charts. I'm using d3 functions that help in chart creation, such as scales, but then using React to generate the svg elements. Here's a great writeup on the approach: http://10consulting.com/2014/02/19/d3-plus-reactjs-for-charting/

Part of why I'm going down this road was for performance - the first version of the app was too slow. It has a lot of elements and a lot of user-interactivity, all client-side. I'm trying to basically recreate the dc.js library in React.

It's a really fun approach and intuitive (more so than d3 alone IMO). Building axes is tedious though, and d3 does it so nicely. I would love d3 to just be able to output a string of svg elements that represent the axis (and maybe other elements) , and I feed it to React to include in the DOM.

I did see this SO question (How to make d3.js generate an svg without drawing it?) and the answer was to append it in the DOM and remove it, or create a DOM fragment. Those approaches go against the React approach and likely negate the performance benefits of React. I also saw jsdom and phantomjs solutions, which will not work in my case.

Can d3 generate svg without appending it to the DOM?

like image 760
Jeff Avatar asked Jun 30 '14 22:06

Jeff


2 Answers

@Lars is correct if you are using traditional means. However, this is definitely possible with 'jsdom'. This library can simulate the DOM and also allows for string input. Which means you could inject the root element into the fake DOM and get a new window element to manipulate. You could then use D3 without changing it's source and using is like normal.

This would allow for the generation of an SVG.

like image 127
max Avatar answered Oct 21 '22 08:10

max


No. D3 by design operates directly on the DOM through its selections. To have it generate string representations instead without modifying the DOM, you would need to modify its source code (and it would be quite a significant modification).

like image 39
Lars Kotthoff Avatar answered Oct 21 '22 08:10

Lars Kotthoff