How to jazz up d3 charts with clipped image and animation in react.js


I wrote this post to show the versatility of react when it comes to displaying d3 charts. Also wanted to show that d3.js can be used more creatively by using its advanced svg features. For this chart I am using the bars from the bar chart as a stencil to cut out a collage from a graphical image. As a bonus the whole thing is responsive.

Be warned this post will be looking at advanced features of svg and I will also assume you know how to create charts with d3.js and react.js. But you can got to the end section to see the demo in play and view the code in codesandbox.

So diving straight into the code. As you can see from section 1] highlighted below, there is an image tag with an attribute ’clipPath’. This tells the browser that there is a clip path with id ‘clip-barchart’ to be used and the browser needs to look for it under the <defs> section of the svg. In section 2] , the <defs> tag will hold the bar chart rendering data for each bar. So in short all we are doing is slightly changing the flow of things when displaying bar charts using d3.js.

…and now for the animation .For this, you need to bolt on the transition related attributes ie easing, duration and delay, to the d3 chained functions. As you can see below, the component component will render the d3 chart when mounted with these animation settings.

.. you can see the code in action below