Skip to content

Use D3.js with React Native

Kejiang edited this page May 31, 2022 · 3 revisions

D3.js is an excellent JavaScript library for visualizing data. However, it could be quite confusing for developers to integrate it within the context of a React.js. In our SoCity dApp, a donut chart showing personal commute data need to be added on the Performance screen by using D3.js. This wiki contains the useful tips to do so.

  1. Understand React's state and lifecycle . In this scenario, we write the chart as Child component and then import Child to Parent Component. So developers need to get a better understanding about react's state and lifecycle to do so.
  2. Use the Scalable Vector Graphics(SVG) to show the donut chart. The SVG has many advantages, such as, scalability, interactivity, easily editable, compact file-size, etc. Especially, the scalability, so it can hand the problem of vector images that is losing quality when being scaled to any dimension through raster images.
  3. Utilize tspan and html to write SVG multiline texts with d3.js. If developers want to write multiline texts in d3.js chart, such as its labels, it can't use the Newline character like "/n" or "/r/n". One of the easiest method is to use tspan and html: .html(function (d) { return "<tspan x='0' dy='-1em'>" + Math.floor(d.data[1]*100)+"%" + "</tspan>" + "<tspan x='0' dy='1em'>" +d.data[0] + "</tspan>";
  4. Put elements on the right or on the left. When adding labels in the chart, it is necessary to put it on the right position: const midangle = d.startAngle + (d.endAngle - d.startAngle) / 2 posC[0] = radius * 1.15 * (midangle < Math.PI ? 1 : -1);

Use D3.js with React Native

Clone this wiki locally