I want to build reusable and very efficient components using D3 and React or Vue.js. The problem is because they both use the virtual DOM, a lot of the power of D3 is lost because I can’t use D3 to update the DOM, if I do so, the Virtual DOM will not track the changes made. I was told to use D3 only for mathematic operations, but when I want to build axes the task was complexe and then forced to use D3 to update the DOM. so, is there any trick to cohabitate D3 with one of the two libraries? and if yes, which one is the best, and why? sorry for my english and thank you in advence.
Asked
Active
Viewed 856 times
0
-
Possible duplicate of [How to generate svg client-side with d3 without attaching it to the DOM (using with React.js)](http://stackoverflow.com/questions/24500071/how-to-generate-svg-client-side-with-d3-without-attaching-it-to-the-dom-using-w) – Abdennour TOUMI Feb 19 '17 at 03:04
-
`react-d3` is already there : https://www.npmjs.com/package/react-d3 – Abdennour TOUMI Feb 19 '17 at 03:05
1 Answers
2
As you said, I would recommand to use D3 only for mathematic operation and let only Vue or React manipulate the DOM. Now D3 is split in small modules so it's easier to use it only for computations.
The advantages I see are :
- Maintainability : someone familiar with Vue or React can understand more easily your component.
- Need for specific algorithm : you can use other computationnal libraries. For instance I made a contours visualization few months ago and needed marching square algorithm that was not yet implemented in d3.
- Ability to use web workers because computations and render are clearly separated.
The main drawback is the lack of available example, but this will increase in time.
For your axis problem, you could use something like this (Vue code) :
HTML template in SVG :
<g v-for="(tick, index) in ticks" v-if="tick.v === 0 || tick.v >= 1" opacity="1" :transform="'translate(50,' + (height - tick.sv) + ')'">
<line stroke="#000" stroke-width="1" x1="0" x2="5"></line>
<text fill="#000" x="-5" alignment-baseline="central">{{tick.f}}</text>
</g>
JS:
const d3scale = require('d3-scale')
const d3array = require('d3-array')
const d3format = require('d3-format')
var yScale = d3scale.scaleLinear()
.domain([0, d3array.max(this.values)])
.range([0, this.height])
const tickFormat = d3format.format('.2s')
vm.ticks = yScale.ticks(5).map(t => {
return {
v: t,
sv: yScale(t),
f: tickFormat(t)
}
})

Nicolas Bonnel
- 191
- 1
- 7
-
2syntax has changed slightly since v2; http://codepen.io/sdras/pen/OWZRZL, https://medium.com/tyrone-tudehope/composing-d3-visualizations-with-vue-js-c65084ccb686 might also help – timelyportfolio Apr 29 '17 at 11:08