The new D3.js Join method is awesome for teaching

30th Jannuary, 2019 - 2 min. read - in Tutorials - Go to Index

The new join method of D3.js simplifies a lot introducing the library to newcomers.

One of the most difficult parts of D3.js to grasp has always been the brilliant enter update exit strategy that manages the different phases required by any dynamic and interactive visualization built with the library.

The very recent 5.8.0 release introduces a new method to simplify that part, adding a very common default behavior for simple representations. No doubt, it’s going to become the preferred way to teach the basics of interactive D3.js visualizations.

Let’s look at the difference, using a very minimal dynamic barchart that is able to adapt based on the dataset changes.

Here the pre-join version (just the relevant part):

var rects = d3.select('svg')
    .selectAll('rect')
    .data(data)

var newrects = rects.enter()
    .append('rect')
    .style('fill', 'red')

rects.merge(newrects)
    .attr('width', d => d.value)
    .attr('height', 20)
    .attr('y', (d, i) => i*20)

rects.exit()
    .remove()

Here, the same functionality with the new method:

d3.select('svg')
    .selectAll('rect')
    .data(data)
    .join('rect')
    .style('fill', 'red')
    .attr('width', d => d.value)
    .attr('height', 20)
    .attr('y', (d, i) => i*20)

Both handle the three different stages when a visualization needs to be updated according to a given dataset, in particular:

Here the complete Codepen, click on the chart to trigger the update:

See the Pen d3-quick-chart-2 by Fabio Franchino (@abusedmedia) on CodePen.

You can check both versions here and here.

Well done, @mbostock.


Spotted a typo or (likely) a grammar error? Send a pull request.